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?
Just call unsubscribe () to cancel the execution. So you are free to that Observable. You can find more about Angular Observables here. That’s it for this tutorial.
In this component we simply call .subscribe () to get the events from our Observables. When first working with Angular and RxJS subscribing directly to the Observable is where most users start. The pros to this are it's simple and works well for single values. The cons to
RxJS have useful operators that we can use in a declarative way to unsubscribe from subscriptions in our Angular project. One of them are the take* family operators:
Using operators from rx.js enables us to make observables complete without calling unsubscribe (). Using those methods instead of calling unsubscribe () always has preference as we have much more control over our subscriptions this way. For each rx.js operator i will include images of rxmarbles.com.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With