Subscribing to observables
We have already learned that an observer needs to subscribe to an observable in order to start getting emitted data. Our products and product-view services currently emit product data using observables. We must modify their respective components to subscribe and get these data:
- Open the
product-list.component.ts
file and create agetProducts
method in theProductListComponent
class:
private getProducts() {
this.productService.getProducts().subscribe(products => {
this.products = products;
});
}
- In the preceding method, we subscribe to the
getProducts
method of theProductsService
class because it returns an observable instead of a plain products array. The products array is returned inside thesubscribe
method, where we set theproducts
component property to the array emitted from the observable. - Modify the
ngOnInit
method so that it calls the newly createdgetProducts
method:
ngOnInit(): void {
this.getProducts();
}
- We could have added...