Posting to the Web API from TodoService

We just updated todo.Services.ts to call the Web API's GET action and fetch Todo items. Now, let's add code to post a new Todo item to the Web API. Follow the given steps to do so:

  1. Open todo.service.ts.
  1. Add the postTodo function that posts a new Todo item to the Web API controller:
     postTodo(todo: Todo): Promise<Todo> { 
var headers = new Headers();
headers.append('Content-Type',
'application/json');
return this.http.post('/api/todos',
JSON.stringify(todo), { headers: headers })
.toPromise()
.then(response => response.json() as Todo)
.catch(this.handleError);
}

This function accepts a Todo item as an argument. It defines the header section with the JSON content type and posts the Todo item using the http service to a Web API asynchronously. The response is converted to Promise and the then method returns a Promise<Todo>.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset