问题
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