anhtv13
anhtv13

Reputation: 1808

Angular 5 can't call method 'post' in WebApi

I want to call a function in Web api from angular 5

This is my function in 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);
  }

This is my function in 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);
        }
    }

I set a breakpoint in Web API but it doesn't receive any call from angular client. However, it works for 'get' method.

Please tell my why function 'post' doesn't work and solution to solve it.

I attach the image below.

enter image description here

Thank you!

Upvotes: 0

Views: 897

Answers (2)

Praveen Kumar
Praveen Kumar

Reputation: 543

Where ever you are calling the createTodo method ensure that you are subscribing. Refer below for code snippet:

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

Upvotes: 1

Hugo Noro
Hugo Noro

Reputation: 3243

I believe the problem you are facing has to do with the mismatch of the sent object and the expected object on Web API.

Have you tried passing the todo object in the body instead of stringifying it?

Try this

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

The other reason for the request not being made at all is if you are not subscribing to it. Don’t forget that Observables are lazy.

Have a look at the documentation

Upvotes: 1

Related Questions