Preparing Services to Interact with the Data
Explore how to prepare Angular services to interact with product data by performing HTTP requests, subscribing to observables, and managing state with behavior subjects. This lesson teaches you to fetch products from an API, handle route parameters, and update a shared cart counter across the app for a seamless e-commerce experience.
We'll cover the following...
We have the relevant components and routing in place now.
On the first view, the home view, we have a simple welcome component called HomeComponent. We get to explore and look for products from this view.
It looks something like this. Now to add a router link to go to the products view, we will add a routerLink directive on the click of this button:
<button class="btn btn-info" routerLink="/products">Search products</button>
The idea now is to fetch the products on the rendering of the products view. We can perform this using either JSON data, an in-memory data store, or a dummy API.
For this application, we will be using the API from jsonplaceholder.com to get the list of products.
As we have looked at lifecycle hooks, we know that on the instantiation of the view, ngOnInit is invoked.
So, we should be performing the request for the data in this method.
Retrieve Products
ngOnInit(): void {
this._getProductList();
...