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.tsfile and create agetProductsmethod in theProductListComponentclass:private getProducts() { this.productService.getProducts().subscribe(products => { this.products = products; }); }In the preceding method, we subscribe to the
getProductsmethod of theProductsServiceclass because it returns an observable instead of a plainproductsarray. Theproductsarray is returned inside thesubscribemethod, where we set theproductscomponent property to the array emitted from the observable.
- Modify the
ngOnInitmethod so that it calls the newly createdgetProductsmethod:ngOnInit()...