q.all for angular2 observables

kdu picture kdu · May 11, 2016 · Viewed 9.3k times · Source

is there something like q.all to resolve all http api requests in angular2?

In angular1, I can do something like this:

var promises = [api.getA(),api.getB()];
$q.all(promises).then(function(response){
    // response[0]  --> A
    // response[1]  --> B
})

In angular2, the http module returns Observable,

api.getA().subscribe(A => {A})
api.getB().subscribe(B => {B})

But I want to resolve A and B together, then do something.

Answer

eko picture eko · May 11, 2016

You will need the .forkJoin operator for that

Observable.forkJoin([observable1,observable2])
       .subscribe((response) => {
          console.log(response[0], response[1]);
       });

You can import the Observable with;

import {Observable} from 'rxjs/Rx';