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

前端 未结 2 1214
夕颜
夕颜 2020-12-10 19:11

I am using Observables, I have a use case where:

  1. I have to get \"pages\" from service which gives me Page[]
  2. For each of those \"pages\" I
2条回答
  •  执念已碎
    2020-12-10 19:49

    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. I'm using it to update the original pages array and return it.

提交回复
热议问题