【发布时间】:2020-02-05 02:23:57
【问题描述】:
我的根(引导)Angular (6.x) 组件中有一个 Observable,AppComponent。
通常,我会在使用生命周期钩子 ngOnDestroy 调用 destroy() 时取消订阅任何打开的订阅。
由于 AppComponent 是应用程序的根,因此永远不会被销毁(除非整个应用程序被销毁),我是否还需要实现 ngOnDestroy 并且我是否需要为取消订阅而烦恼?
我无法找到这个看似常见的确切场景的答案。
例子:
export class AppComponent implements OnInit, OnDestroy {
private tokenSubscription: Subscription;
constructor(private dataSvc: DataService) { }
ngOnInit() {
this.tokenSubscription = this.dataSvc.myObservable.subscribe((val) => {
// do stuff
});
}
ngOnDestroy() {
this.tokenSubscription.unsubscribe(); // Do I need this in root component?
}
}
谢谢!
【问题讨论】:
标签: angular typescript rxjs observable