Search code examples
angularrxjssubscription

Unsubscribe from Angular's Location service


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?


Solution

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