退订 Angular 的定位服务
Unsubscribe from Angular's Location service
我正在使用 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改变时,代码继续执行,即使页面不同,甚至没有加载这个组件。
如何取消订阅位置事件?
调用 subscribe
将 return 一个允许未来取消订阅的对象的引用。
ngOnInit(): void {
this.locationSubscription = this.location.subscribe(event => {
if (event.type === 'hashchange') {
this.doSomething();
}
});
}
ngOnDestroy(): void {
this.locationSubscription.unsubscribe();
}
1.You 可以使用来自 rx/js 的订阅接口:
从 "rxjs/Subscription";
导入 { ISubscription }
2.Create 私有变量为:
私人订阅:ISubscription;
3.Subscribe 到返回的 observable:
this.subscription = this.location.subscribe(事件 => {
if (event.type === 'hashchange') {
this.doSomething();
}
});
4.Unsubscribe轻松:
ngOnDestroy() {
this.subscription.取消订阅();
}
我正在使用 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改变时,代码继续执行,即使页面不同,甚至没有加载这个组件。
如何取消订阅位置事件?
调用 subscribe
将 return 一个允许未来取消订阅的对象的引用。
ngOnInit(): void {
this.locationSubscription = this.location.subscribe(event => {
if (event.type === 'hashchange') {
this.doSomething();
}
});
}
ngOnDestroy(): void {
this.locationSubscription.unsubscribe();
}
1.You 可以使用来自 rx/js 的订阅接口: 从 "rxjs/Subscription";
导入 { ISubscription }2.Create 私有变量为:
私人订阅:ISubscription;
3.Subscribe 到返回的 observable: this.subscription = this.location.subscribe(事件 => {
if (event.type === 'hashchange') {
this.doSomething();
}
});
4.Unsubscribe轻松:
ngOnDestroy() {
this.subscription.取消订阅();
}