Angular 组件在被销毁后仍在监听订阅

Ray*_*uin 4 rxjs angular

角 5

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

我的服务

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

...
}
Run Code Online (Sandbox Code Playgroud)

我的组件

ngOnInit() {
     this.globalVarsService.selectedDepartment$.subscribe( selectDepartment => {
        this.refreshReportData();
    });
}
Run Code Online (Sandbox Code Playgroud)

我可能需要点击 3 次,MyComponent但如果我更新selectedDepartment,订阅仍将触发并this.refreshReportData执行。显然我不想要这个,因为它是完全不必要的额外 HTTP 调用。

我尝试实施onDestroy以验证组件销毁是否在我导航时发生并且确实发生了。所以从我的角度来看,我销毁的组件似乎仍然处于活动状态并监听订阅事件。也没有unsubscribe可用的方法,this.globalVarsService.selectedDepartment$因此我也无法将其放入我的onDestroy方法中。

我该怎么办?

Fat*_*med 7

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

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

ngOnDestroy() {
  this.subscription.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)