在angular 6 rxjs流中进行异步调用的最佳方法

在angular 6 rxjs流中进行异步调用的最佳方法,rxjs,angular6,Rxjs,Angular6,考虑调用4个不同的httpget调用以从数据库获取4个不同计数的场景。 编写代码的最佳逻辑是什么目前我编写的代码如下所示 getfirstCount() { this.http.post('ulr1',request,{headers:headers}) .subscribe(response => { dataCount1 = response.count }, error => { co

考虑调用4个不同的httpget调用以从数据库获取4个不同计数的场景。 编写代码的最佳逻辑是什么目前我编写的代码如下所示

getfirstCount()
{
     this.http.post('ulr1',request,{headers:headers})
      .subscribe(response => {
          dataCount1 = response.count
        },
        error => {
          console.log(error);
        },
        () => {
          this.getSecondCount();
        }
      )
}

如何使用rxjs streams实现上述场景如果您的呼叫必须一个接一个地进行,您可以使用
flatMap
链接您的呼叫:

getfirstCount(){
返回此.http.post('ulr1',请求,{headers:headers})//{
dataCount1=response.count
},
错误=>{
console.log(错误);
},
() => {
这是getSecondCount();
}
)
}
并以这种方式使用它:

getfirstCount()
.flatMap((dataFirstCount)=>getSecondCount(dataFirstCount))
.flatMap(…)
.subscribe(/*handle dataFourthCount*/)

您可以使用forkJoin同时执行所有4个调用:

以下语句将在4个调用全部完成且无错误时收到结果。如果希望在其中一个失败时获得部分结果,则需要在每个单独的http调用上使用catchError

    forkJoin(
        this.httpClient.get('uri_1'),
        this.httpClient.get('uri_2'),
        this.httpClient.get('uri_3'),
        this.httpClient.get('uri_4')
    ).pipe(catchError(err => {
        console.log(err);
    })).subscribe((joined: [Object, Object, Object, Object]) => {
        // handle array of results
    })

恐怕这行不通
getfirstMap
返回订阅,因为您在该函数中订阅。因此,您不能在返回时使用
flatMap
。然后,如果需要顺序执行,最好使用
concatMap
而不是
flatMap