首页 > 解决方案 > Angular 多个订阅然后执行操作

问题描述

我有一个使用订阅从 API 请求数据的函数。我正在尝试重新编写它,以便在所有 API 调用完成后返回一个布尔值。有没有更好的方法来写这个?

我当前的代码:

public res1=null;
public res2=null;

getData(){
 this.svc.getData1().subscribe(x={this.res1=x;})
 this.svc.getData2().subscribe(x={this.res2=x;})
}

我正在考虑尝试创建一个 Observable 来监听嵌套订阅的更改:(未经测试的代码!)

getData(): Observable<boolean>{
 this.svc.getData1().subscribe(x=>{
   this.res1=x;
   this.svc.getData2().subscribe(x=>{this.res2=x; 
     return true;
   })
 })
)

}

标签: angularrxjsobservable

解决方案


一种方法是使用 combineLatest。当所有可观察对象都发出一个值时,Combine latest 会发出一个值。

combineLatest(observeable1$, observable2$).subscribe(
  // when both have submitted a value. return what you like.
);

如果你的 observable 只会解决一次。您也可以使用 forkJoin。这类似于 promise.All


推荐阅读