问题
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