Multitut
Multitut

Reputation: 2169

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?

Upvotes: 17

Views: 19719

Answers (1)

Picci
Picci

Reputation: 17762

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.

Upvotes: 24

Related Questions