调用内部订阅是个好方法吗? [英] Is it good way to call subscribe inside subscribe?

查看:55
本文介绍了调用内部订阅是个好方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将来自三个不同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?

推荐答案

正确的方法是以某种方式组合各种可观察对象,然后订阅整个流程—如何组成它们取决于您的确切要求.

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

如果每个都取决于上一个的结果:

If each depends on the result of the previous:

this.service.service1().pipe(
  flatMap((res1) => this.service.service2(res1)),
  flatMap((res2) => this.service.service3(res2))
).subscribe((res3) => {
  // Do something with res3.
});

...等等.构成可观察对象的运算符有很多.

... and so on. There are many different operators to compose observables.

这篇关于调用内部订阅是个好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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