[Fixed] Angular wait for multiple http requests to complete

Issue

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

Solution

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];
});

Leave a Reply

(*) Required, Your email will not be published