【问题标题】:Angular/RxJs - Unsubscribing dependent http services using take(1)?Angular/RxJs - 使用 take(1) 取消订阅依赖的 http 服务?
【发布时间】:2020-03-12 06:16:11
【问题描述】:

--Component.ts--

 getGenCoreLabs() {
    this.checkinService
      .getLaboratories()
      .pipe(
        switchMap(outerResp => {
          const total = outerResp.headers.get(outerResp.headers.get('total'));
          return this.checkinService.getGenCoreLabs(total);
        }),
        take(1)
      )
      .subscribe(resp => {
        this.apiResponse = resp;
        this.areaList = this.apiResponse.map(labName => {
          return labName.Name;
        });
        this.areaListIds = this.apiResponse.map(labGuid => {
          return labGuid.Guid;
        });
      });
  }

在我的 component.ts 文件中的上述代码中,单次 take(1) 是否足以取消订阅相关的 http 服务?或者我是否也必须在 service.ts 文件中的第二个服务(getGenCoreLabs)中调用 take(1) ? (请参阅下面的代码以供参考)

--Service.ts--

public getGenCoreLabs(total: number): Observable<CoreLaboratoryData> {
    const url = `/core/laboratories?per-page=${total}`;
    return this.httpService.get(url).pipe(take(1));
  }

【问题讨论】:

  • 您不需要显式取消订阅 http 订阅,因为它们只发出一次然后完成或出错。在这两种情况下,您都不需要取消订阅take(1)
  • 你能再解释一下吗? @Picci
  • 不久前我对此做了深入的回答stackoverflow.com/a/60466443/5367916

标签: angular service rxjs take


【解决方案1】:

当 observable 是有限序列时,您不需要取消订阅。 HTTP 请求就是这种情况,它只会发出一个值。

同样的情况,例如 timer(1000),它只在 1000 毫秒后发出一个值。

有关您应该退订或不需要退订的不同情况的更多详细信息,请查看 Netanel Basal 的 When to Unsubscribe in Angular

所以你的代码可能是:

getGenCoreLabs() {
  this.checkinService.getLaboratories().pipe(
    switchMap(outerResp => {
      const total = outerResp.headers.get(outerResp.headers.get('total'));
      return this.checkinService.getGenCoreLabs(total);
    }),
  ).subscribe(resp => {
    ...
  })
}

【讨论】:

    【解决方案2】:

    一个 Observable 可以做 3 件事:通知、错误和完成。

    一旦 Observable 出错或完成,它就不能再恢复,即它不能再通知任何值。您不需要取消订阅已出错或已完成的 Observable 的订阅,因为它们不能再发出。如果您对处理此类通知不再感兴趣,您需要取消订阅您知道可以再次通知的 Observables。

    如果你将一个 http 请求建模为一个 Observable,就像在 Angular 中一样,你所拥有的是一个 Observable,它只能做以下两件事之一:

    1. 在响应到达然后完成时通知响应
    2. 出现问题时出错

    在这两种情况下,Observable 都不会再通知了,所以你不需要取消订阅。

    您可以查看this answer了解更多详情。

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 2018-01-17
      • 2019-07-12
      • 2017-11-21
      • 2020-02-14
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多