Adam
Adam

Reputation: 37

Angular wait for multiple http requests to complete

I have a very similar problem to this post: Angular wait for multiple http requests to complete and then fire the last one

I would like to achieve literally the same thing like this:

forkJoin(
  this.data.getCodes('medical'),
  this.data.getCodes('delay'),
  this.data.getCodes('disability'),
  this.data.getCodes('district'),
).subscribe(([medicalData, delayData, disabilityData, districtData]) => {
  this.Medical = medicalData;
  this.Delays = delayData;
  this.Disability = disabilityData;
  this.District = districtData;

  // make your last http request here.
});

With the exception that I don't know how many http request will I make. My input would be an array of urls and the api would return me a character object for each call and i would store them. But I don't know how many urls will I pass, maybe 10, maybe 0, depending on the array's lenght

Upvotes: 1

Views: 1625

Answers (2)

Barremian
Barremian

Reputation: 31105

The array's length doesn't matter when using forkJoin. In case of dynamic length, you could assign the response from forkJoin to a single variable instead of using spread syntax as shown.

Also you ought to use a higher order mapping operator like switchMap to map to another observable instead of nested subscriptions.

urlArray = [
  this.http.get('url1'),
  this.http.get('url2'),
  this.http.get('url3'),
  this.http.get('url4'),
  ...
];

forkJoin(urlArray).pipe(
  switchMap((res: any) =>
    this.http.get('finalUrl').pipe(       
      map((final: any) => ([res, final])) // <-- do this if you need response from `forkJoin`
    );
  )
).subscribe({
  next: ([resArr, resFinal]) => {
    // resArr - [
    //   response from this.http.get('url1'), 
    //   response from this.http.get('url2'), 
    //   response from this.http.get('url3'), 
    //   ...
    // ];

    // resFinal - response from this.http.get('finalUrl')
  },
  error: (error: any) => {
    // handle error
  }
);

Upvotes: 2

Weakipedia
Weakipedia

Reputation: 38

ForkJoin actually accepts an array of observables parameter so you could do something like this.

const arr = [this.data.getCodes('medical'), this.data.getCodes('delay')];

//add more observables to your arrays
arr.push(this.data.getCodes('disability'));

//use spread operator on subscribe response
forkJoin(arr).subscribe(([...arrayResp])=>{

   //arrayResp will contain array of response
   let theFirstResponse = arrayResp[0];
});

Upvotes: 1

Related Questions