Angular等待多个http请求完成,然后触发最后一个

时间:2018-10-29 18:12:55

标签: angular angular6

我有4个http请求。三个接收查询值,而第四个接收实际的表格数据。

他们这样走:

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

如何使第四个get请求等到前三个请求完成?

预先感谢

2 个答案:

答案 0 :(得分:3)

您应该使用forkJoin来获得所需的结果。 forkJoin等待所有可观察对象完成,然后再发出值。示例:

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

答案 1 :(得分:2)

您可以使用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
});