取消订阅 Angular 的定位服务 [英] Unsubscribe from Angular's Location service

查看:70
本文介绍了取消订阅 Angular 的定位服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular 的 (v5.2.2) 位置服务来跟踪特定组件中的 URL 更改.

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

我想在组件销毁时取消订阅 Location 事件.

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

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

但我收到错误:

this.location.unsubscribe is not a function

问题是当URL改变时代码继续执行,甚至认为页面不同,甚至没有加载这个组件.

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?

推荐答案

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

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

这篇关于取消订阅 Angular 的定位服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆