RxJS:在每次返回并行http请求时更新客户端

RxJS: Updating client on each return of parallel http requests

本文关键字:请求 http 更新 客户端 并行 返回 RxJS      更新时间:2023-12-08

目标:使用RxJS并行运行多个异步http请求,并在每个请求返回后触发回调。

例如:

getSomeData() {
    Observable.forkJoin(
        this.http.get('/somethingOne.json').map((res:Response) => res.json()),
        this.http.get('/somethingTwo.json').map((res:Response) => res.json())
    ).subscribe(
      data => {
        this.somethingOne = data[0]
        this.somethingTwo = data[1]
      },
      err => console.error(err)
    );
}

上面的代码将并行运行http.get请求,并将响应映射到json,但在每个http响应上,我都希望调用我创建的函数。有没有任何方法可以将回调函数传递给传递给forkJoin方法的http请求?

这样行吗?只是在当前选择器函数的主体中执行函数。(这里可能有一些语法错误,因为我没有使用ES6)。包括两个版本,具体取决于您想要如何使用该函数,但想法很清楚:使用map选择器函数来运行您想要的任何逻辑。

getSomeData() {
    Observable.forkJoin(
        this.http.get('/somethingOne.json').map((res:Response) => {myFunction(res); return res.json()}),
        this.http.get('/somethingTwo.json').map((res:Response) => myOtherFunction(res.json()))
    ).subscribe(
      data => {
        this.somethingOne = data[0]
        this.somethingTwo = data[1]
      },
      err => console.error(err)
    );
}