我有一个使用订阅从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;})
}我正在考虑尝试创建一个监听对嵌套订阅的更改的可观察性:(不是测试代码!)
getData(): Observable<boolean>{
this.svc.getData1().subscribe(x=>{
this.res1=x;
this.svc.getData2().subscribe(x=>{this.res2=x;
return true;
})
})
)}
发布于 2019-05-30 21:50:10
其中一种方法是使用combineLatest。当所有可观察对象都发出一个值时,合并最新值。
combineLatest(observeable1$, observable2$).subscribe(
// when both have submitted a value. return what you like.
);如果你的可观察对象只会解析一次。您也可以使用forkJoin。它类似于promise.All
发布于 2019-05-30 22:24:00
您可以使用合并运算符来合并可观察对象并并行订阅它们。
getData(): Observable<boolean>{
let isCompleted: Observable<boolean>;
merge(this.svc.getData1(), this.svc.getData2()).subscribe(
(val) => {console.log(val) },
(err) => { console.log(err) },
()=>{isCompleted = of (true); });
return isCompleted;
}https://stackoverflow.com/questions/56379485
复制相似问题