简体   繁体   中英

Angular RXJS, how do I get all data in subscribe after using multiple mergeMap calls (sequentially)?

I'd like to get all data similar to how 'forkJoin' does it after making multiple HTTP calls sequentially using MergeMap.

this.dataService.getData1().pipe(
      mergeMap(response1 => this.dataService.getData2()),
      mergeMap(response2 => this.dataService.getData3()),
      mergeMap(response3 => this.dataService.getData4()),
    ).subscribe(

    //How do I get response1, response2, response3 and response4 here?

 )

If no observable's parameter depend on the previous call

you can use concat , which will play the observables is a sequence, each time waiting on the previous to finish (unlike merge )

var arr = [
  this.dataService.getData1(),
  this.dataPublicationsService.getData2(),
  this.dataPublicationsService.getData3(),
  this.dataPublicationsService.getData4(),
];
concat(...arr).pipe(toArray()).subscribe((a) => console.log(a));

If each call depends on the previous one there is no "clean" way to do it, you have to pass the data youself.

One way to achieve this is use forkJoin and the spread operator

class Foo {
  dataService: { getData1: () => Observable<number> };
  dataPublicationsService: {
    getData2: () => Observable<string>;
    getData3: () => Observable<number>;
    getData4: () => Observable<object>;
  };

  bar() {
    this.dataService
      .getData1()
      .pipe(
        mergeMap((response1) =>
          forkJoin([of(response1), this.dataPublicationsService.getData2()])
        ),
        mergeMap((rest) => // rest is [number, string]
          forkJoin([of([...rest]), this.dataPublicationsService.getData3()])
        ),
        mergeMap((rest) => rest is [number, string, number]
          forkJoin([of(...rest), this.dataPublicationsService.getData4()])
        )
      )
      .subscribe((rest) => {
         // [number, string, number, object]
      });
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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