代码之家  ›  专栏  ›  技术社区  ›  anhtv13

Angular 5无法在WebApi中调用方法“post”

  •  0
  • anhtv13  · 技术社区  · 7 年前

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

    这是我在api中的函数。服务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”功能不起作用,以及解决方法。

    我附上下面的图片。

    enter image description here

    非常感谢。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Hugo Noro    7 年前

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

    你试过通过 todo 对象而不是字符串化它?

    试试这个

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

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

    看看 documentation

        2
  •  1
  •   Praveen Kumar    7 年前

    无论您在何处调用createTodo方法,请确保您正在订阅。请参阅下面的代码片段:

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