Unsubscribe from Angular's Location service

*爱你&永不变心* 提交于 2019-12-11 15:37:54

问题


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();
        }
    });
}

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

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

But I get the error:

this.location.unsubscribe is not a function

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?


回答1:


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();
}



回答2:


1.You can use ISubscription interface from rx/js: import { ISubscription } from "rxjs/Subscription";

2.Create a private variable as:

private subscription: ISubscription;

3.Subscribe to the observable returned: this.subscription = this.location.subscribe(event => {

    if (event.type === 'hashchange') {
        this.doSomething();
    }
});

4.Unsubscribe easily:

ngOnDestroy() {

this.subscription.unsubscribe();

}



来源:https://stackoverflow.com/questions/48729990/unsubscribe-from-angulars-location-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!