我想知道是否有一些rxjs操作我可以在forkJoin之后调用以了解我的并行异步任务是否已经完成,所以我可以在angular2模板中使用类似* ngIf =“loaded | async”的东西.
我提出了一个解决方案,但对我来说似乎很麻烦.
我敢打赌,有一种更清洁的rxJS方式.
plunkr如果你需要它:
https://plnkr.co/edit/UFVCJpjKAEGguMls5eIl?p=preview
public 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()); }
this.loaded = Observable.combineLatest( this.something1(),() => { // now we know we have finished return true } );
解决方法
使用combineLatest.这样的事情应该有效:
this.loaded = this.something1().combineLatest( this.something2(),function (s1,s2) { return true } ).take(1);
还要注意,我最后调用take(1),以确保我们只发出一个事件,因为它只会被加载一次.