取消订阅 Angular 的定位服务

问题描述:

我正在使用 Angular 的 (v5.2.2) 位置服务来跟踪特定组件中的 URL 更改.

I'm using Angular's (v5.2.2) Location service to track URL changes in a specific component.

ngOnInit(): void {
    this.location.subscribe(event => {
        if (event.type === 'hashchange') {
            this.doSomething();
        }
    });
}

我想在组件销毁时取消订阅 Location 事件.

I want to unsubscribe from the Location events when the component is destroyed.

ngOnDestroy(): void {
    this.location.unsubscribe();
}

但我收到错误:

this.location.unsubscribe is not a function

问题是当URL改变时代码继续执行,甚至认为页面不同,甚至没有加载这个组件.

The problem is that the code continues to be executed when the URL is changed, even thought the page is different and this component is not even loaded.

如何取消订阅位置事件?

How can I unsubscribe from the Location events?

调用 subscribe 将返回对允许将来取消订阅的对象的引用.

Calling subscribe will return a reference to an object that allows future unsubscribe.

ngOnInit(): void {
    this.locationSubscription = this.location.subscribe(event => {
        if (event.type === 'hashchange') {
            this.doSomething();
        }
    });
}

ngOnDestroy(): void {
    this.locationSubscription.unsubscribe();
}