End interval when route changes in Angular 2

本秂侑毒 提交于 2019-11-30 20:19:56

This should do it:

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

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

You could clear the interval from this hook. Mine is controlled from the 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);
     }
}

Maybe for what you want is better OnDeactivate from angular2/router (and maybe also OnActivate depending on your usecase) because you said you want to end the timer when the user leaves the route If I understand it correctly.

export Compnent implements OnInit, OnDeactivate {
    private timer;

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

    routerOnDeactivate() {
        clearInterval(this.timer);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!