Angular Wait for Multiple Http Requests to Complete and Then Fire the Last One

I have 4 http requests. Three receives lookup values while the 4th one gets actual form data.

They go like this:

   let medicalData = this.data.getCodes('medical').subscribe((data: {}) => {
     console.log('med');
       this.Medical = data;
        });
   let delayData = this.data.getCodes('delay').subscribe((data: {}) => {
    console.log('del');
          this.Delays = data;
           });
   let disabilityData = this.data.getCodes('disability').subscribe((data: {}) => {
    console.log('dis');
            this.Disability = data;
             });
   let districtData = this.data.getCodes('district').subscribe((data: {}) => {
    console.log('dist');
              this.District = data;
               });

How can I make the 4th get request wait till the first three requests are complete ?

Thanks in advance

2 Answers

You should use forkJoin to achieve the desired result. forkJoin waits for all obesrvables to complete before emitting a value. Example:

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.
});
5

You can use forkJoin

let medicalData = this.data.getCodes('medical');
let delayData = this.data.getCodes('delay');
let disabilityData = this.data.getCodes('disability')
Observable.forkJoin([medicalData, delayData, disabilityData]).subscribe((responses)=>{
    // responses is an array of responses for the individual observables
    // Execute the code you want to run after the three observables here
});
6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest