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:
- Open todo.service.ts.
- 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>.