2

I want to know whether the Multiple request :

if my $http request 1 start , let's say $http request 1 ends and tried to call $http request 2. my question how can i create a multiple request ?

for example : call $http request 1 then $http request 2.

sebaferreras
  • 44,206
  • 11
  • 116
  • 134
Mahmoud Ismail
  • 1,617
  • 4
  • 27
  • 51

1 Answers1

5

As I understand, you're trying to make more than one http request and then process the response when all those request have ended. For instance, you may need to load data from more than one source, and delay the post-loading logic until all the data has loaded.

If that's the case, you could use ReactiveX Observables because it provides a method called forkJoin() to wrap multiple Observables.

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class MultipleHttpService {

  constructor(private http:Http) { }

  // If any single request fails, the entire operation will result in an error state.
  getData0AndData1() {
    return Observable.forkJoin(
      this.http.get('/app/data0.json').map((res:Response) => res.json()),
      this.http.get('/app/data1.json').map((res:Response) => res.json())
    );
  }

}

Then you could get all the data by subscribing to that observable:

// Code in your page ...
this.myMultipleHttpService.getData0AndData1()
    .subscribe(
      data => {
        this.data0= data[0]
        this.data1 = data[1]
      },
      err => console.error(err)
    );
sebaferreras
  • 44,206
  • 11
  • 116
  • 134
  • thank you for your response, but iv'e got an error `Property 'forkJoin' does not exist on type 'typeof Observable` – Mahmoud Ismail Aug 09 '16 at 08:34
  • it's done thank you ,more question if i want to make a call using `Concat` , can i do that with loading ? – Mahmoud Ismail Aug 09 '16 at 09:19
  • @sebaferreras is there a way for an index in the resulting array to "dissolve" if the this.http.get fails? So for example, if the this.http.get fails for data1, then the length of the resulting array would be 1 instead accounting for the 2 calls that were made inside the Observable.forkJoin( ... ) argument block? – Benjamin McFerren Sep 23 '16 at 05:19
  • Glad to hear that it helped @MuhammadNadeem :) – sebaferreras Oct 19 '17 at 08:16