【问题标题】:Angular 5 can't call method 'post' in WebApiAngular 5 无法在 WebApi 中调用方法“post”
【发布时间】:2018-09-13 12:19:48
【问题描述】:

我想从 Angular 5 调用 Web api 中的函数

这是我在 api.service.ts 中的函数:

//it works
public getAllTodos() {
    return this.http
      .get(API_URL + '/todos/')
      .map(response => {
        const todos = response.json();
        return todos.map((todo) => new Todo(todo));
      })
      .catch(this.handleError);
  }
  
  //it doesn't work
  public createTodo(todo: Todo) {
    let headers = new Headers({ 'Content-Type': 'application/json' });        
    //let options = new RequestOptions({ headers: headers });
    let payload = JSON.stringify(todo);
    return this.http
      //.post(API_URL + '/todos/', JSON.stringify(todo), options)
      .post(API_URL + '/todos/', payload, {headers: headers})
      .map(response => {
        return new Todo(response.json());
      })
      .catch(this.handleError);
  }

这是我在 Web Api 中的功能:

[HttpGet]
    [Route("todos")]
    public HttpResponseMessage GetAllTodos()
    {
        try
        {                
            List<Todo> todos = manager.GetAll().ToList();
            return Request.CreateResponse(HttpStatusCode.OK, todos);
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
        }
    }

    [HttpPost]
    [Route("todos")]
    public HttpResponseMessage CreateTodo([FromBody] Todo todo)
    {
        try
        {
            Todo td = new Todo() { title = todo.title, complete = todo.complete };
            int id = manager.CreateTodo(td);
            return Request.CreateResponse(HttpStatusCode.OK, id);
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
        }
    }

我在 Web API 中设置了一个断点,但它没有收到来自 Angular 客户端的任何调用。但是,它适用于 'get' 方法。

请告诉我为什么函数'post'不起作用以及解决它的解决方案。

我附上下面的图片。

谢谢!

【问题讨论】:

  • 您是否检查了开发者的工具和网络选项卡?
  • @brk 即使我在 Chrome 中设置断点并运行,也没有请求在网络选项卡中“发布”功能。
  • 你是怎么调用createTodo函数的?
  • 和上面代码中的'get'方法一样
  • 1) 您的网络选项卡在 devtools 中显示什么? 2)你在WebApi端启用了CORS吗?

标签: javascript angular asp.net-web-api


【解决方案1】:

我相信您面临的问题与发送对象和Web API 上的预期对象不匹配有关。

您是否尝试过在正文中传递 todo 对象而不是对其进行字符串化?

试试这个

post(API_URL + '/todos/', todo, {headers: headers})

根本没有提出请求的另一个原因是您没有订阅它。不要忘记Observables 是懒惰的。

看看documentation

【讨论】:

  • 不幸的是,它仍然不起作用。网络标签不显示任何“发布”请求。
  • 不显示错误。客户没有要求,我不明白为什么:(
  • 等一下正在订阅 createTodo 方法吗?除非您进行订阅,否则不会触发请求
  • 你能详细解释一下吗?请告诉我如何解决?
  • 我已更新我的答案以包含文档链接。但基本上你需要做的是无论你在哪里调用 createTodo 方法,你都需要执行 createTodo.subscribe()。除非你这样做,否则请求不会被触发,因为 http 返回一个 observable。这是一个冷的可观察对象,这意味着除非有人订阅它,否则它不会做任何事情。
【解决方案2】:

无论您在哪里调用 createTodo 方法,请确保您正在订阅。代码sn-p参考下面:

this._service.createTodo(todoobject).subscribe(success=>{},error=>{});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 2016-11-22
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 2018-10-10
    相关资源
    最近更新 更多