q.all for angular2 observables

2019-03-17 23:06发布

问题:

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.

回答1:

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';