Angular Typescript:结合2个api调用一次Promise

时间:2019-05-29 07:42:40

标签: angular typescript

因此,目前我的服务中有两种方法可以进行API调用,如下所示。 它们都返回与JSON相同类型的对象,这是一个控件

如何以方法执行“ getControls”,然后执行“ getControlsECC”,然后将它们加在一起并返回的方式组合它们?

getControls(): Promise<Control[]> {
    return this.http.get(this.controlsUrl)
           .toPromise()
           .then(response => response.json() as Control[])
           .catch(this.handleError);
}

getControlsECC(): Promise<Control[]> {
  return this.http.get(this.controlsECC)
         .toPromise()
         .then(response => response.json() as Control[])
         .catch(this.handleError);

}

2 个答案:

答案 0 :(得分:0)

doBoth() {
  return forkJoin(
    this.getControls().pipe(map(response => response.json())),
    this.getControlsECC().pipe(map(response => response.json())),
  ).toPromise()
    .catch(this.handleError);
}

getControls() {
    return this.http.get<Control[]>(this.controlsUrl);
}

getControlsECC() {
  return this.http.get<Control[]>(this.controlsECC);
}

答案 1 :(得分:0)

在这种情况下,您可以使用forkJoin

    forkJoin(
      this._myService.makeRequest('Request One', 2000),
      this._myService.makeRequest('Request Two', 1000),
      this._myService.makeRequest('Request Three', 3000)
    )
    .subscribe(([res1, res2, res3]) => {
      this.propOne = res1;
      this.propTwo = res2;
      this.propThree = res3;
    });
  }

可以找到详细信息here