Angular 2 路线改变时的结束间隔

End interval when route changes in Angular 2

我在路由器插座内的 Angular 2 组件中启动了一个计时器。

setInterval(() => {
    ...
}, 10000);

当我离开嵌入了组件的路线时,计时器并没有停止。我怎样才能做到这一点?

应该这样做:

routerOnActivate() {
  this.timer = setInterval(()=>{
                ...
            }, 10000);
}

routerOnDeactivate() {
  clearInterval(this.timer);
}

您可以从此挂钩中清除间隔。 我的是由 component/view.

控制的
export classTestInterval implements OnInit, OnDestroy{
     public timerInterval:any;
     ngOnInit(){
       // Need interval scope in the component could be from somewhere else, but we need scope to be able to clear it on destruction of component.
       this.timerInterval = setInterval(function(){...},10000);
     }
     ngOnDestroy() {
        // Will clear when component is destroyed e.g. route is navigated away from.
        clearInterval(this.timerInterval);
     }
}

也许你想要的更好 OnDeactivate 来自 angular2/router (也可能 OnActivate 取决于你的用例)因为你说你想在用户离开时结束计时器路线 如果我没理解错的话。

export Compnent implements OnInit, OnDeactivate {
    private timer;

    ngOnInit(){
        this.timer = setInterval(_ => {
            // disco
        }, 10000);
    }

    routerOnDeactivate() {
        clearInterval(this.timer);
    }
}