【问题标题】:Angular Components still listening to subscriptions after being destroyed [duplicate]Angular 组件在被销毁后仍在监听订阅 [重复]
【发布时间】:2018-10-17 15:06:30
【问题描述】:

Angular 5

我遇到的问题是,当我离开一个组件时,该组件仍在侦听服务订阅更新并采取行动。

我的服务

export class GlobalVarsService {
  private selectedDepartment = new BehaviorSubject<number>(null);
  selectedDepartment$ = this.selectedDepartment.asObservable();

...
}

我的组件

ngOnInit() {
     this.globalVarsService.selectedDepartment$.subscribe( selectDepartment => {
        this.refreshReportData();
    });
}

我可能与MyComponent 相距3 次点击,但如果我更新selectedDepartment,订阅仍将触发,this.refreshReportData 将执行。显然我不希望这样,因为它是完全没有必要的额外 HTTP 调用。

我已经尝试实现onDestroy 来验证当我导航时组件破坏正在发生并且确实发生了。因此,从我的角度来看,我被破坏的组件似乎仍然处于活动状态并正在侦听订阅事件。 this.globalVarsService.selectedDepartment$ 上也没有可用的 unsubscribe 方法,所以我也不能将它放入我的 onDestroy 方法中。

我该怎么办?

【问题讨论】:

标签: angular rxjs


【解决方案1】:

是的,你必须在 ngOnDestroy 中取消订阅,但是如果你使用 Async Pipe,它会自动处理它

import { Subscription } from "rxjs/Subscription";
private subscription: Subscription ;
ngOnInit() {
 this.subscription = this.globalVarsService.selectedDepartment$.subscribe( selectDepartment => {
    this.refreshReportData();
});
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}

【讨论】:

  • 我在 stackoverflow 上读到了一些关于处理组件订阅的推荐方法是使用 takeUntil 运算符。我发现这种方式也比跟踪每个订阅更优雅。看到这个答案:stackoverflow.com/questions/42490265/…
猜你喜欢
  • 2018-09-18
  • 2014-04-02
  • 1970-01-01
  • 2020-11-09
  • 2020-04-05
  • 2021-02-25
  • 2016-12-06
  • 2020-11-15
  • 2020-07-11
相关资源
最近更新 更多