【问题标题】:(Angular 2/4/5/6) Nested subscribe methods with multiple http requests(Angular 2/4/5/6)具有多个 http 请求的嵌套订阅方法
【发布时间】:2019-05-07 16:19:12
【问题描述】:

我需要在订阅方法中调用订阅方法。

在第一个 subscribe 方法中,它返回给我一个 deviceid,它随后在第二个 subscribe 方法中使用。

result=[];
idArray=[2,4];

this.subscription =
    this.quoteService.get(this.quoteid) //first api call
     .subscribe((quote: Quote) => {   
       this.deviceid = quote["deviceid"]; 
       this.faultService.get(this.deviceid) //second api call
        .pipe(first())
        .subscribe((faultGroup: FaultGroup[]) => {
        faultGroup.forEach(({ faults }) => {
          //execute logic for 2nd subscription
          if (faults) {
            faults
              .filter(
                ({ id }) => this.idArray.indexOf(id) > -1,
              )
              .forEach(fault => this.result.push(fault.name));
          }
          //end of logic
        });
      });
    subscription.unsubscribe();
  }
});

有人可以教我如何使用 flatMap/switchMap 来避免使用嵌套订阅吗?感谢您的帮助!

【问题讨论】:

  • 什么是first()?同步方法?

标签: angular angular6 subscription subscribe


【解决方案1】:

这里你的要求是从第二个API返回结果,只是调用第二个API,你需要第一个的结果。为此,switchMap() 最适合您。按照代码中的说明使用它。

this.subOb = this.quoteService.get(this.quoteid) //first api call
    .pipe(switchMap((quote: Quote) => {
          // result of first API call here
        this.deviceid = quote["deviceid"];
          // you need to return the second observable from inside the switcMap
          // and this will only be executed after the first Observable(first API call) is finished
        return this.faultService.get(this.deviceid) //second api call
          // need some mode logic after second API call is done? call first()?
          // map the result with a pipe
            .pipe(map(secondData) => { 
                  // If you aren't manipulating the data 
                  // to be returned, then use tap() instead of map().
                return data;
            })

    }))
        .subscribe((data) => {
            // only one subscription is required.
            // this will have data from second API call
        })

使用ngOnDestroy() 挂钩到unsubcribe() 以获得Subscriptions。我看到您正在将订阅分配给一个变量,并且可能使用它来取消订阅。如果您的 Observable 多次发射(我认为它不会),那么在第一次发射期间,当涉及到 subscribe() 时,“订阅”变量将是未定义的。

ngOnDestroy() {
    if (this.subOb) {
        this.subOb.unsubscribe();
    }
}

在此处查看示例:https://stackblitz.com/edit/swicthmap?file=src%2Fapp%2Fapp.component.ts

它包含两个开关映射的实现,分析两者并使用任何适合你的套件。

【讨论】:

  • 嗨 xyz 感谢您的帮助!我可以知道是否可以跳过点击和地图部分并直接进行第二次订阅?例如返回 this.faultService.get(this.deviceid).subscribe(etc.)
  • @iBlehhz 如果你想在second请求之后执行任何逻辑,那么你必须使用maptap我们没有在第二个 API 调用上进行订阅,switchMap 期望一个 Observable,而不是一个订阅作为返回。我们只在外部 API 调用上进行订阅。
  • @iBlehhz: 方法first() 做了什么?
  • @iBlehhz:见示例中添加的链接
  • 嘿,非常感谢!!在你的帮助下我想通了。非常感谢你,你是一个救生员:DDD
猜你喜欢
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-14
  • 1970-01-01
相关资源
最近更新 更多