【问题标题】:Unsubscribe from Angular's Location service取消订阅 Angular 的定位服务
【发布时间】:2018-07-21 15:35:57
【问题描述】:

我正在使用 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 改变时代码继续执行,即使页面不同并且甚至没有加载这个组件。

如何取消订阅位置事件?

【问题讨论】:

  • 保留对订阅的引用:this.locationSubscription = this.location.subscribe(...);
  • 谢谢@jonrsharpe。我将发布完整的代码作为答案。

标签: angular rxjs subscription


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    2.创建私有变量为:

    私人订阅:ISubscription;

    3.订阅observable返回: this.subscription = this.location.subscribe(event => {

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

    4.轻松退订:

    ngOnDestroy() {

    this.subscription.unsubscribe();

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-04
      • 2019-01-18
      • 2018-04-19
      • 2021-11-18
      • 1970-01-01
      相关资源
      最近更新 更多