Combining http observables using forkjoin

I am trying to avoid nested observables using forkjoin . The current (nested) version is as follows:

  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(); }); }); } 

I can rewrite the first part as:

 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()) ) 

But I'm not sure how to add the .subscribe component to access data_changes and data_all .

Looking at another example, I know that it should look something like .subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]}); but I'm not sure how to adapt it to my example.

+7
angular typescript observable ionic2
source share
1 answer

Try using combineLatest instead of forkJoin :

With combineLatest :

 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); }); 

You can also handle it with forkJoin, but forkJoin will return data when all calls are completed and return the result, but in combLatest. When any observable emits a value, emits the last value from each.

With forkJoin :

 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); }); 

Call both and check the console log, you get a view.

+15
source

All Articles