Update task with the HTTP client
- βοΈUpdate a task with the HTTP clientLearn how to update a task to a list using the HTTP client in an Angular application.
Besides targeting the update of a task rather than its creation, this lesson will be quite similar to the previous one:
- you will update the TaskService
- you will update the TaskFormComponent by caring about the asynchronous nature of the HTTP request
The TaskService
Based on the HTTP protocol, you will use the put function to add a task to the list: http.put(). This function expects 2 parameters:
- The URL of the API server, this URL will include the task id to update:
http://localhost:3000/tasks/${task.id}
- The task to send to the server
π Instructions
-
Update the task.service.ts file.
Update the TaskFormComponent
Letβs update the TaskFormComponent to use this new function. Th easiest way to do so would be to apply the same logic as in the previous lesson, by updating the submit function to make an API call and navigate to the list page. It would result in the following code:
It works but itβs not the best way to do it as we are duplicating the navigation logic. If the list page path changes, we will have to update it in two places. Letβs handle it by changing the submit function:
- create a variable whose value will be either the updateTask or addTask function, its value will be an Observable you can subscribe to.
- subscribe to this variable and navigate to the list page.
π Instructions
-
Update the task-form.component.ts file.
βοΈ What you learned
You learned how to send a PUT request with HttpClient to update a task in an Angular application.