I have the following code which consists of multiple subscribes. What I need to achieve is like this :
- Subscribe to activatedRoute to get User and Product data.
- With the product data returned, subscribe to getSeller service by using the product data.
- Subscribe to getRating service by using the seller data returned.
My question : is there any better way to perform these nested subscription? is it a good practice to do like this?
this.activatedRoute.data.pipe(
map((data) => {
this.user = data['user'];
this.product = data['product'];
return this.product;
})
).subscribe(result => {
if (this.product === null) {
this.router.navigate(['/home']);
} else {
this.displayCurrency = this.dataService.getCurrencySymbolById(this.product.currency);
this.userService.getUser(this.product.createdBy).subscribe(seller => {
this.seller = seller;
this.ratingService.getRatingByUserId(seller.id).subscribe(rating => {
this.rating = rating;
})
});
}
});
Technically, nesting subscribe works, but there is a more elegant and systematic way of handling this. You should really learn more about your RxJS operators.
First, we use mergeMap to map over the observable values from the activatedRoute into an inner observable.
Then, we use forkJoin to combine the observables into a single value observable, thus returning the value itself on the
.subscribe()
EDIT: Turns out I have misread the original question, as getRatingsByUserId is dependent on getUser. Let me make some changes. Either ways, I will leave the code above as it is, as it is good for OP's reference.
Use switchMap to switch to a new observable.