Retrieve the task list
- ✔️Retrieve tasksRetrieve the list of tasks from the fake API server
Update the TaskService
The HttpClient service exposes multiple functions to make HTTP requests to a server. In this chapter, we will use its get function to query the task list from the API server.
This function takes the API server endpoint as a parameter: http://localhost:3000/tasks
.
That’s the URL it’ll query to get the task list.
This new getTasks defines the contract with the API server:
- it makes a GET request
- it expects an array of Task objects as a response
- it communicates with the API server at
http://localhost:3000/tasks
URL.
🎓 Instructions
-
Update the the
src/app/task-list/task-list.component.ts
file.
Subscription
Calling the getTasks function won’t trigger the API request immediately and as it’s not trigger yet, the observable won’t emit any value. Let’s trigger what we call a subscription to the observable to start the request.
We subscribe like we would subscribe to a newspaper. We request the last issue of the newspaper and only once it’s available, it’s delivered and we can read it.
How to subscribe
There are multiple ways to subscribe to an observable. For the given situation, Let’s use the async pipe in the HTML template.
Like the date pipe used earlier, the async pipe role is to transform the data before displaying it. Here it’s role will be to subscribe to the observable and returns the list of tasks once available.
While there are alternatives, the async pipe is the recommended way to subscribe to an observable in the HTML template. You’ll discover the alternative at the end of this page.
🎓 Instructions
-
Update the the
src/app/task-list/task-list.component.html
file.
Alternative
The alternative to using the async pipe is to subscribe to the observable in the component.
This is done by calling the subscribe function on the observable and passing a function as a callback parameter. This callback will be called once the data is available.
This subscription will be used in the ngOnInit function of the TaskListComponent class.
🎓 Instructions
-
Update the the
src/app/task-list/task-list.component.ts
file.
Pitfalls
While subscribing to the observable in the component is a valid solution, it misses some optimizations that the async pipe provides. It also requires more code for the same result.
✔️ What you learned
In this chapter, you learned one of the key features of Angular: how to query data from an API server!