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

查看:22
本文介绍了在 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(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.

这是一篇关于switchMap的好文章.

This is a nice article about switchMap.

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

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