Best way to chain observable subscriptions in Angular?

半腔热情 提交于 2020-06-14 06:41:07

问题


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?


回答1:


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(this.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 swichMap formerly known as flatMap.



来源:https://stackoverflow.com/questions/51108217/best-way-to-chain-observable-subscriptions-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!