往回路由第四个时,Angular创建多个订阅

时间:2018-11-26 18:51:11

标签: javascript angular typescript timer ngrx

在组件的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());
    });
  }

dead

0 个答案:

没有答案