(Angular 2/4/5/6) 两种(或更多)内部订阅方法和一种外部订阅方法

(Angular 2/4/5/6) Two (or more) inner subscribe methods and one outer subscribe method

我想弄清楚如何使用外部订阅方法调用 2 个内部订阅方法。我总共想进行 3 次 api 调用,但是,2 次 api 调用取决于 1 次 api 调用的结果。

this.subscription = this.quoteService //1st api call
    .get(this.quoteid)
    .pipe(
    switchMap((q: TradeinQuote) => {
        const quote = q["quote"];
        //execute code using quote
        this.price = quote["price"];
        this.retrieveDeviceid = quote["deviceid"];
        return this.faultService.get(this.retrieveDeviceid); //2nd api call
        }),
    ).subscribe(
        (faultGroup: FaultGroup[]) => {
        //execute logic for 2nd api call
    });
);

所以在我从第一个 api 调用中得到 this.retrieveDeviceid 之后,我想再进行 2 个 api 调用,其中一个在 faultService 上(如图所示)和第二个在 deviceService

E.g. this.deviceService.get(this.retrieveDeviceid)

目前显示的代码仅处理 1 个内部订阅和 1 个外部订阅。为了进行另一个内部订阅,我是否必须使用 mergeMap 或 forkJoin,我该怎么做?感谢您的指导!!

使用siwtchMapforkJoin

this.subscription = this.quoteService.get(this.quoteid).pipe(
  switchMap(response => forkJoin(
    of(response),
    this.faultService.get(response.quote.deviceid),
    this.deviceService.get(response.quote.deviceid),
  ))
).subscribe(([res1, res2, res3]) => { ... });

forkJoin 结合了冷 observables(即不再发出值的 observables)的结果。

编辑

要管理单个调用的一些逻辑,您可以使用 tap :

this.subscription = this.quoteService.get(this.quoteid).pipe(
  tap(response => { /* execute some code with your first HTTP call response */ }),
  switchMap(response => forkJoin(
    of(response),
    this.faultService.get(response.quote.deviceid),
    this.deviceService.get(response.quote.deviceid),
  ))
).subscribe(([res1, res2, res3]) => { ... });