Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 768
w2olves Avatar asked Oct 29 '18 18:10

w2olves


1 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.
});
like image 120
Teddy Sterne Avatar answered Sep 28 '22 07:09

Teddy Sterne