简体   繁体   English

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

[英]RxJS: Updating client on each return of parallel http requests

Goal: Run a number of async http requests in parallel using RxJS and fire callback after each request is returned. 目标:使用RxJS并行运行许多异步http请求,并在返回每个请求后触发回调。

For example: 例如:

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)
    );
}

The above code will run the http.get requests in parallel and map the response to json, but on each http response I want a function I created to be called. 上面的代码将并行运行http.get请求,并将响应映射到json,但是在每个http响应上,我都希望调用我创建的函数。 Is there any way to pass a callback function to the http requests that are passed to the forkJoin method? 有什么方法可以将回调函数传递给传递给forkJoin方法的http请求吗?

Would that work? 那行得通吗? Just executing your function in the body of your current selector function. 只需在当前选择器函数的主体中执行函数即可。 (There might be some syntax errors here, as I don't use ES6). (这里可能存在一些语法错误,因为我不使用ES6)。 Included two versions depending on how you want to use that function, but the idea is clear : use your map selector function to run any logic you want. 包括两个版本,具体取决于您要如何使用该函数,但思路很明确:使用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)
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM