Angular 2中路线变化时的结束间隔

时间:2016-02-22 18:40:08

标签: javascript angular typescript angular2-routing

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

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

当我离开嵌入组件的路径时,计时器不会退出。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:13)

您可以清除此挂钩的间隔。 我可以从组件/视图中控制。

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);
     }
}

答案 1 :(得分:7)

这应该这样做:

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

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

答案 2 :(得分:5)

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

export Compnent implements OnInit, OnDeactivate {
    private timer;

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

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