在 subscribe 中调用 subscribe 是个好方法吗? [英] Is it good way to call subscribe inside subscribe?
问题描述
我需要将三个数据从三个不同的 API 传递给一个函数:
I need to pass three data to one function from three different APIs:
this.service.service1().subscribe( res1 => {
this.service.service1().subscribe( res2 => {
this.service.service1().subscribe( res3 => {
this.funcA(res1, res2, res3);
});
});
});
在订阅内订阅是一个好习惯吗?
Is it a good practice to subscribe inside a subscribe?
推荐答案
正确的方法是以某种方式组合各种 observable 然后订阅整个流程——如何组合它们将取决于您的确切需求.
The correct way is to compose the various observables in some manner then subscribe to the overall flow — how you compose them will depend on your exact requirements.
如果您可以并行执行所有操作:
If you can do them all in parallel:
forkJoin(
this.service.service1(), this.service.service2(), this.service.service3()
).subscribe((res) => {
this.funcA(res[0], res[1], res[2]);
});
如果每个都依赖于前一个的结果,则可以使用mergeMap
(以前称为flatMap
)或switchMap
:
If each depends on the result of the previous, you can use mergeMap
(formerly known as flatMap
) or switchMap
:
this.service.service1().pipe(
mergeMap((res1) => this.service.service2(res1)),
mergeMap((res2) => this.service.service3(res2))
).subscribe((res3) => {
// Do something with res3.
});
...等等.有许多操作符可以组成 observables 以覆盖许多不同的场景.
... and so on. There are many operators to compose observables to cover lots of different scenarios.
这篇关于在 subscribe 中调用 subscribe 是个好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!