javascript - Angular 在返回和第四次路由时创建多个订阅
问题描述
在我的组件的 ngOnInit 中,我调用了轮询方法。在我的 ngOnDestroy 中,我取消订阅此方法。现在,当我再次路由回同一个组件并触发我的 ngOnInit 时,我现在有 2 个订阅。每当我离开组件时,我都会在我的 ngOnDestroy 中取消订阅。这种模式继续下去,每次访问相关组件时,我的订阅量都会增加一个。我该如何摆脱这种行为?
请让我知道我是否可以提供更多代码或细节以使事情更清楚。提前致谢!
请参见下面的代码:
// app.component.ts
ngOnInit() {
// init of my store, selecting the selector and subscribing to it
this.store.select(fromStore.getAllVehicleDetails).subscribe(data => {
this.updateVehicleStates(data);
this.updateFavoriteVehicles();
this.vehicleDetail = this.getVehicleDetail(this.selected);
});
this.store.select(fromStore.getFavVehiclesId).subscribe(data => {
for (let i = 0; i < data.length; i++) {
this.favVehicleIdMap.set(data[i].id, data[i]);
}
});
this.subscribeToData();
}
ngOnDestroy() {
console.log('dead');
this.timerSubscription.unsubscribe();
}
/* Poll-function */
private subscribeToData(): void {
this.timerSubscription = Observable.timer(0, 10000).subscribe(() => {
this.store.dispatch(new fromStore.LoadVehicleDetails());
this.store.dispatch(new fromStore.LoadFavVehiclesId());
});
}
解决方案
推荐阅读
- c# - 为什么这个 WaitLock 卡住了?
- python - 在我的寡妇 7 专业机器上安装 python 时遇到问题
- python - 必须以管理员-python 运行
- node.js - 从 MongoDB 聚合函数接收的数组不可迭代
- python - python中的双重调用
- javascript - 如何使用 JS/CSS 将数字设置为 PRE
- sql - 当没有相关记录时,无法使用日期过滤器显示记录
- java - 是否可以根据实际类中的局部变量为方法调用返回模拟对象?
- python-3.x - Frozen Issue while opening an existing file
- python - BrowserMob Proxy with Python - The Browsermob-Proxy server process failed to start - Seeing Operation not permitted in server.log