24

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.

kdu
  • 1,259
  • 4
  • 12
  • 18

2 Answers2

33

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';
eko
  • 39,722
  • 10
  • 72
  • 98
  • 4
    Do you know also RXJS solution for the other variant of $q.all() call, where you can pass an Object rather than an array? It's more elegant approach because you can later address promises by name and not by index. – ŁukaszBachman Oct 12 '17 at 09:42
1

Angular < 6:

import {Observable} from 'rxjs/Observable';
    ...
    return Observable.forkJoin(
        this.http.get('someurl'),
        this.http.get('someotherurl'));

Angular >= 6:

import {forkJoin} from 'rxjs';
...
return forkJoin(
    this.http.get('someurl'),
    this.http.get('someotherurl'));
Andris
  • 3,895
  • 2
  • 24
  • 27