等待Angular 5中的多个Observable

时间:2018-09-13 18:05:11

标签: angular typescript async-await angular5 observable

我是Angular和TypeScript的新手,所以问题听起来可能是错误的。 我正在使用Visual Studio Code和Angular 5(ng-version =“ 5.2.11”)。

我需要“等待”直到我对api的调用结束并返回结果,而无需将所有内容包装在巨型“ .subscribe”中。 我所拥有的:

exampleMethod(): SettingsClass {
const myComplexObject: SettingsClass = {
  field1: predefined.field1,
  field2: predefined.field2,
  field3: isComplexCalculationsNecessary ? this.CallApi_1(predefined.paramForField3) : predefined.field3,
};

return myComplexObject;
}

以前,我在“ 预定义”中拥有所有参数,但是现在我需要从外部源中查询一个(或多个),并立即从方法中返回“ myComplexObject”(进行其他一些api调用,或其他组件,甚至接口,但我需要完全定义此对象,并设置所有参数)。我可以将代码“上下颠倒”,然后将所有内容放入大的“ .subscribe”中,但是我没有这样做,因为在某些时候,我还需要其他参数来进行查询,所有这些都将中断。 如何编写对api的调用,以避免每次需要添加新的外部调用时都重写我的所有代码?像这样:

CallApi_1(paramForField3: string): Observable<int> {
return this.http.get(`${httpConfig.route}?$apply=filter${paramForField3}/groupby${httpConfig.groupingParam}`);
}

或者也许

CallApi_1(paramForField3: string): Observable<int> {
return this.ExternalCallsService.GetParam3Information(paramForField3).subscribe(res => 
.GetParam3Information contains the same http call as above, but I need to do
something to return this result outside, I don't know what);
}

我要寻找的是国王:

field3: isComplexCalculationsNecessary ? **await** this.CallApi(predefined.paramForField3) : predefined.field3,

我目前正在尝试使用具有与Observables一起使用的有趣选项(例如“ forkJoin”)的“ rxjs”,但是我不确定我的方向是否完全正确,也许这种技巧是不可能的,或者对Observables的理解是不对的,我需要将复杂的逻辑转移到后端吗?请提出建议。

再次要注意的是,简单的“ .subscribe”不是我想要的,因为在所有订阅示例中,我们都不返回值,而是将其分配给某些全局变量或直接分配给html-element,不是我所需要的,我需要获取价值并继续与外部资源一样尽快回馈它。

2 个答案:

答案 0 :(得分:0)

您可以使用zip或forkjoin运算符(它们相似但不相同),也可以链接http调用:

this.http.get1( url1, headers ).subscribe(
   data => {
      this.data1 = data;
      this.http.get2( url2, headers ).subscribe(
         data => {
            this.data2 = data;
         },
         error2{
            // do something on error2
         }
      )
   },
   error1 => {
      // do something on error1
   }
)

这不是很好,但是可以。我记得使用zip解决相同的问题。

编辑:我找到了zip示例

     const  tpcomprob$ = this.data.getTPComprob( this.tpcomprobsId);
     const  comprobs$ = this.data.getComprobs(this.tpcomprobsId); 

     this.sbsComprobs = zip(tpcomprob$, comprobs$, (tpcomprob: any, comprobs: any) => ({tpcomprob, comprobs}))
                       .subscribe(pair => {
                          this.tpcomprob = pair.tpcomprob;
                          this.comprobs = pair.comprobs;

        },
        error => {this.httpError = error ;})
  });

答案 1 :(得分:0)

forkJoin 是最简单的。

var _arr = [];

_arr.push(this.mySvc.callback01());
_arr.push(this.mySvc.callback02());

forkJoin(_arr).subscribe(resList=>{
    //-- the response will be in array
});