首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Location.subscribe()泄漏

Location.subscribe()泄漏
EN

Stack Overflow用户
提问于 2017-06-09 06:55:59
回答 1查看 3.5K关注 0票数 0

我使用Location.subscribe()来检测"back“按钮。https://angular.io/docs/ts/latest/api/common/index/Location-class.html

代码语言:javascript
复制
export class PathLocationComponent {
  location: Location;
  constructor(location: Location) { 
     location.subscribe(val => console.log(val))//output popstate
  }
}

但是,当我重复按“后退”和“向前”按钮时,日志的数量会增加。我认为Locaion.subscribe()在漏水。但是我不知道如何发布它,因为Location类没有取消订阅()。

如何释放Location.subscribe()或防止泄漏?

我想使用PlatformLocation.onPopState()。https://angular.io/docs/ts/latest/api/common/index/PlatformLocation-class.html

但是,文档说明如下

代码语言:javascript
复制
This class should not be used directly by an application developer. Instead, use Location.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-09 07:06:37

你可以试试这个:

代码语言:javascript
复制
import {Subscription} from 'rxjs/Subscription';

export class PathLocationComponent implements OnDestroy {
location: Location;
private subscription: Subscription;

      constructor(location: Location) {
        this.subscription = location.subscribe(val => console.log(val))//output popstate
      }

     ngOnDestroy(): void {
        this.subscription.unsubscribe();
     }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44451244

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档