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

时间:2018-10-01 12:18:01

标签: rxjs angular6

考虑调用4个不同的 http get调用以从数据库中获取4个不同计数的方案。 编写代码的最佳逻辑是什么,目前我的写法如下所示

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

如何使用 rxjs流

实现上述方案

2 个答案:

答案 0 :(得分:1)

您可以使用forkJoin同时执行所有4个调用: https://www.learnrxjs.io/operators/combination/forkjoin.html

当所有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
    })

答案 1 :(得分:0)

如果必须一个接一个地拨打电话,则可以使用flatMap将通话链接起来:

getfirstCount() {
 return this.http.post('ulr1',request,{headers:headers}) // <-- you have to returne an observable
  .subscribe(response => {
      dataCount1 = response.count
    },
    error => {
      console.log(error);
    },
    () => {
      this.getSecondCount();
    }
  )
}

并以这种方式使用它:

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