取消订阅Angular的位置服务

时间:2018-02-11 09:12:50

标签: angular rxjs subscription

我使用Angular(v5.2.2)定位服务来跟踪特定组件中的网址更改。

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

我希望在销毁组件时取消订阅位置事件。

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

但我收到错误:

this.location.unsubscribe is not a function

问题是当URL被更改时代码会继续执行,即使页面不同也不会加载此组件。

如何取消订阅位置事件?

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:0)

1.您可以使用rx / js的ISubscription接口: 从“rxjs / Subscription”导入{ISubscription};

2.创建一个私有变量:

私人订阅:ISubscription;

3.订阅返回的观察者: this.subscription = this.location.subscribe(event => {

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

4.轻松取消订阅:

ngOnDestroy(){

this.subscription.unsubscribe();

}

相关问题