(角度2/4/5/6)两个(或多个)内部订阅方法和一个外部订阅方法

时间:2019-01-14 10:07:21

标签: angular http subscribe switchmap

我试图弄清楚如何用外部订阅方法调用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,该如何进行呢?感谢您的指导!

1 个答案:

答案 0 :(得分:1)

使用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合并了冷可观测值(即不再发出值的可观测值)的结果。

编辑

要管理单个呼叫的某些逻辑,可以使用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]) => { ... });