我想知道是否有一些rxjs操作我可以在forkJoin之后调用以了解我的并行异步任务是否已经完成,所以我可以有类似* ngIf =" loading |异步"在angular2模板中。
我提出了一个解决方案,但对我来说似乎很麻烦。 我打赌有一种更清洁的rxJS方法。
如果你需要,可以选择: https://plnkr.co/edit/UFVCJpjKAEGguMls5eIl?p=previewpublic loaded:Observable<boolean>;
constructor(private http:Http) {
// This is the best solution I could come up with. Is there a cleaner way
// by just calling some operation after forkJoin instead of building my own observable?
this.loaded = Observable.create((observer) => {
observer.next(false);
Observable.forkJoin(
this.something1(),
this.something2(),
() => {
// now we know we have finished
observer.next(true);
}
).subscribe();
});
}
something1() {
return this.http.get('test1.json').map((res) => res.json());
}
something2() {
return this.http.get('test2.json').map((res) => res.json());
}
更新 根据Luka的评论,试过这个。效果很好。好多了:
this.loaded = Observable.combineLatest(
this.something1(),
this.something2(),
() => {
// now we know we have finished
return true
}
);
答案 0 :(得分:4)
使用combineLatest
。这样的事情应该有效:
this.loaded = this.something1().combineLatest(
this.something2(),
function (s1, s2) { return true }
).take(1);
另请注意,我最后调用了take(1)
,以确保我们只发出一个事件,因为它只会加载一次。
答案 1 :(得分:1)
我认为这可能更直接:
this.loaded = Observable.forkJoin(this.something1(), this.something2()).map(_=>true);