我正在尝试使用ngOnDestroy删除路由更改时的所有事件侦听器,但我找不到办法来执行此操作。
每个侦听器中的回调是我的组件中带有'this'绑定的方法。
我的代码目前看起来像这样:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-partners-promote-geolocation',
templateUrl: './partners-promote-geolocation.component.html'
})
export class PartnersPromoteGeolocationComponent implements OnInit {
constructor () {}
ngOnInit() {
document.addEventListener('scroll', this.infoWindowPositionState.bind(this))
document.addEventListener('click', this.infoWindowVisibilityState.bind(this))
}
ngOnDestroy () {
document.removeEventListener('scroll', this.infoWindowPositionState.bind(this))
document.removeEventListener('click', this.infoWindowVisibilityState.bind(this))
}
infoWindowPositionState () {
(...)
}
infoWindowVisibilityState () {
(...)
}
}
我可以正常添加事件侦听器,但是当路由更改时,不会删除这些事件。在我的React项目中,这就像使用componentDidMount和componentWillUnmount的魅力一样,我可以防止内存泄漏,但我没有成功地以角度完成此任务。
我怎么能在Angular 5中做到这一点?
谢谢!