Merging http observables using forkjoin
我正在尝试通过使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | this.http.get('https://testdb1.firebaseio.com/.json').map(res => res.json()).subscribe(data_changes => { this.http.get('https://testdb2.firebaseio.com/.json').map(res => res.json()).subscribe(data_all => { /* Do this once resolved */ this.platform.ready().then(() => { this.storage.set('data_changes', data_changes); this.storage.set('data_all', data_all); document.getElementById("chart").innerHTML =""; this.createChart(); }); }); }, err => { this.platform.ready().then(() => { console.log("server error 2"); document.getElementById("chart").innerHTML =""; this.createChart(); }); }); } |
我可以将第一部分重写为:
1 2 3 4 | Observable.forkJoin( this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()), this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json()) ) |
但是我不确定接下来如何添加
再看一个例子,我知道它看起来应该像
尝试使用
使用
1 2 3 4 5 6 7 8 9 10 | const combined = Observable.combineLatest( this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()), this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json()) ) combined.subscribe(latestValues => { const [ data_changes , data_all ] = latestValues; console.log("data_changes" , data_changes); console.log("data_all" , data_all); }); |
您也可以通过forkJoin处理它,但是forkJoin将在所有调用完成后返回数据并返回result,但在CombineLatest中,当任何可观察到的对象发出一个值时,则从每个对象中发出最新的值。
使用
1 2 3 4 5 6 7 8 9 10 | const combined = Observable.forkJoin( this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()), this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json()) ) combined.subscribe(latestValues => { const [ data_changes , data_all ] = latestValues; console.log("data_changes" , data_changes); console.log("data_all" , data_all); }); |
同时调用这两个命令并查看控制台日志,您会发现想法。