在Angular中链接可观察订阅的最佳方法? [英] Best way to chain observable subscriptions in Angular?

查看:63
本文介绍了在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;
            });
    });

我正在使用Angular v6和AngularFire2.

I am using Angular v6 and AngularFire2.

两个端点(getPayment和getGym)都返回对象.还有什么更优雅的方法可以在不将一个呼叫嵌套到另一个呼叫的情况下做到这一点?

Both endpoints (getPayment and getGym) return objects. Is there any more elegant way to do this without nesting one call inside another?

推荐答案

在线上有很多资源可以帮助您了解如何使用rxjs解决这种情况.

There are many resources available online to get an understanding of how this kind of scenarios can be addressed with rxjs.

通常,您最终会像这样使用switchMap

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;
)

我故意跳过了valueChanges()通话.我对它的功能一无所知,但在被动世界中听起来并不正确.

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.

这是关于swichMap 的不错的文章,以前称为flatMap.

这篇关于在Angular中链接可观察订阅的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆