Best way to chain observable subscriptions in Angular?
11,995
There are many resources available online to get an understanding of how this kind of scenarios can be addressed with rxjs.
Usually you end up using switchMap
like this
this.paymentService.getPayment(this.currentUser.uid, this.code)
.pipe(
switchMap(payment => this.gymService.getGym(payment.gym))
)
.subscribe(
this.gym = gym;
)
I have skipped on purpose the valueChanges()
call. I do not have any idea of what it does, but it does not sound as right in a reactive world.
This is a nice article about switchMap
.
Related videos on Youtube
Comments
-
Multitut almost 2 years
I have always nested subscriptions when I need to call a resource after getting the result of another one, like so:
this.paymentService.getPayment(this.currentUser.uid, this.code) .valueChanges() .subscribe(payment => { this.payment = payment; this.gymService.getGym(this.payment.gym) .valueChanges() .subscribe(gym => { this.gym = gym; }); });
I am using Angular v6 and AngularFire2.
Both endpoints (getPayment and getGym) return objects. Is there any more elegant way to do this without nesting one call inside another?
-
Vikas almost 6 years
-
Vikas
-
-
Mohamad Al Asmar over 3 yearsyou should do > return this.gymService.getGym(this.payment.gym)
-
Wintermute over 2 yearsIsn't the assignment
this.payment = payment;
missing now? -
Picci over 2 years@Wintermute you are right, if you need the payment in the component you need the assignement