Angular2 Observable - Await multiple function calls before proceeding Angular2 Observable - Await multiple function calls before proceeding angular angular

Angular2 Observable - Await multiple function calls before proceeding


I have been doing this with forkJoin

import {Observable} from 'rxjs/Observable';import 'rxjs/add/observable/forkJoin';Observable.forkJoin(  this.http.get('./friends.json').map((res: Response) => res.json()),  this.http.get('./customer.json').map((res: Response) => res.json())).subscribe(res => this.combined = {friends: res[0].friends, customer: res[1]});

Some more info here: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http


In RxJS v6 and later you can do this more eloquently with zip.

    import { zip } from 'rxjs';    const promise1 = yourSvc.get(yourFavoriteAPI.endpoint1);    const promise2 = yourSvc.get(yourFavoriteAPI.endpoint2);    const promises = zip(promise1, promise2);    promises.subscribe(([data1, data2]) => {      console.log(data1);      console.log(data2);    });

While the result is the same, I find zip preferable to forkJoin since zip is more universal and can handle new values from the observables.

Details from the rxjs documentation:

The zip operator will subscribe to all inner observables, waiting foreach to emit a value. Once this occurs, all values with thecorresponding index will be emitted. This will continue until at leastone inner observable completes.