简体   繁体   English

使用 Angular RxJs Observables 处理多个 http 请求并等待所有请求完成

[英]Handle multiple http requests and wait for all to complete using Angular RxJs Observables

I am using Observables, I have a use case where:我正在使用 Observables,我有一个用例,其中:

  1. I have to get "pages" from service which gives me Page[]我必须从给我Page[]服务中获取“页面”
  2. For each of those "pages" I have to get the "sections" from other service对于每个“页面”,我必须从其他服务中获取“部分”
  3. Also on subscribe of all those "sections" I have to do some action based on the data returned.同样在订阅所有这些“部分”时,我必须根据返回的数据执行一些操作。

The concern is once all of those requests are completed then have to do some action.问题是一旦所有这些请求都完成了,就必须采取一些行动。

you need use mergeMap and forkJoin你需要使用mergeMapforkJoin

When using forkJoin you can fire parallel request at the same time and it will wait till all requests are completed.使用forkJoin您可以同时触发并行请求,它会等待所有请求完成。

this.http.get('/api/pages/')
    .map((res: any) => res.json())
    .mergeMap((pages: any[]) => {
      if (pages.length > 0) {
        return Observable.forkJoin(
          pages.map((page: any) => {
            return this.http.get('/api/sections/' + page_id)
              .map((res: any) => {
                let section: any = res.json();
                // do your operation and return
                return section;
              });
          });
        );
      }
      return Observable.of([]);
    });
}

In general when nesting async calls try to stay as flat as possible.一般来说,在嵌套异步调用时尽量保持平坦。 Otherwise, you're creating callback hell which make things even more complicated than just with regular iterative code:否则,您将创建回调地狱,这使事情比使用常规迭代代码更加复杂:

this.http.get('/api/pages/')
  .map((res: Response) => res.json())
  .concatMap((pages: Page[]) => {
    const observables = pages.map(p => this.http.get('whatever' + p.id));

    return Observable.forkJoin(observables, (...results) => 
      results.map((result, i) => {
        pages[i].sections = result;
        return pages[i];
      })
    )
  })
  .subscribe(pagesWithSections => ...);

The forkJoin() operator takes as argument a selector function that lets you work with the results of all the source Observables. forkJoin()运算符将选择器函数作为参数,该函数可让您处理所有源 Observables 的结果。 I'm using it to update the original pages array and return it.我正在使用它来更新原始pages数组并返回它。

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

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