0

I am trying to combine observables, where each observables gets the input in a for loop. My problem is, that I would know how to do it without the for loop, if I know the array the for loop would loop over in advance -> I would just put everything inside the combineLatest.

Does anyone know how I would do this, if I do not know the size of sections?

Many thanks in advance!

getArticleSectionsContent(pageId: string): Observable<any> {
 return this.getArticleSections(pageId).pipe(
  switchMap(sections => {
    return combineLatest([
      this.getArticleSectionContent(pageId, sections[0].index),
      this.getArticleSectionContent(pageId, sections[1].index),
      this.getArticleSectionContent(pageId, sections[2].index),
    ]).pipe(
      map(([a, b, c]) => {
        return { a, b, c };
      })
    );
  })
 );
}
JilReg
  • 382
  • 1
  • 3
  • 16

1 Answers1

0

If you do not know the size of sections, loop through your array with the map operator to convert it into an array of observables, like this:

getArticleSectionsContent(pageId: string): Observable<any> {
 return this.getArticleSections(pageId).pipe(
  switchMap(sections => {
    const articleSectionContentObsArray = sections.map(section => {
        return this.getArticleSectionContent(pageId, section.index);
    });
    return combineLatest(articleSectionContentObsArray);
  })
 );
}
Quentin Fonck
  • 1,286
  • 9
  • 14