Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to chain observable subscriptions in Angular?

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?

like image 355
Multitut Avatar asked Jun 29 '18 19:06

Multitut


People also ask

How to unsubscribe from an observable in angular?

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.

How to get events from observables in AngularJS?

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

How to unsubscribe from subscriptions in angular using RxJS?

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:

How to make observables complete without calling unsubscribe()?

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.


1 Answers

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.

like image 130
Picci Avatar answered Oct 22 '22 07:10

Picci