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.

Share:
11,995

Related videos on Youtube

Multitut
Author by

Multitut

merge delete

Updated on June 04, 2022

Comments

  • Multitut
    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?

  • Mohamad Al Asmar
    Mohamad Al Asmar over 3 years
    you should do > return this.gymService.getGym(this.payment.gym)
  • Wintermute
    Wintermute over 2 years
    Isn't the assignment this.payment = payment; missing now?
  • Picci
    Picci over 2 years
    @Wintermute you are right, if you need the payment in the component you need the assignement