【发布时间】:2018-07-21 15:35:57
【问题描述】:
我正在使用 Angular 的 (v5.2.2) 位置服务来跟踪特定组件中的 URL 更改。
ngOnInit(): void {
this.location.subscribe(event => {
if (event.type === 'hashchange') {
this.doSomething();
}
});
}
我想在组件被销毁时取消订阅 Location 事件。
ngOnDestroy(): void {
this.location.unsubscribe();
}
但我得到了错误:
this.location.unsubscribe is not a function
问题是当 URL 改变时代码继续执行,即使页面不同并且甚至没有加载这个组件。
如何取消订阅位置事件?
【问题讨论】:
-
保留对订阅的引用:
this.locationSubscription = this.location.subscribe(...); -
谢谢@jonrsharpe。我将发布完整的代码作为答案。
标签: angular rxjs subscription