首页 > 解决方案 > 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());
    });
  }

死的

标签: javascriptangulartypescripttimerngrx

解决方案


推荐阅读