在 Angular 中链接可观察订阅的最佳方式?

Mul*_*tut 13 javascript observable rxjs typescript angular

当我需要在获取另一个资源的结果后调用资源时,我总是嵌套订阅,如下所示:

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;
            });
    });
Run Code Online (Sandbox Code Playgroud)

我正在使用 Angular v6 和 AngularFire2。

两个端点(getPayment 和 getGym)都返回对象。有没有更优雅的方法来做到这一点而不将一个调用嵌套在另一个调用中?

Pic*_*cci 12

有许多在线资源可以帮助您了解如何使用 rxjs 解决此类场景。

通常你最终会switchMap像这样使用

this.paymentService.getPayment(this.currentUser.uid, this.code)
.pipe(
   switchMap(payment => this.gymService.getGym(this.payment.gym))
)
.subscribe(
   this.gym = gym;
)
Run Code Online (Sandbox Code Playgroud)

我故意跳过了valueChanges()电话。我不知道它的作用是什么,但它在反应性世界中听起来并不正确。

这是一篇关于swichMap.