End interval when route changes in Angular 2

后端 未结 3 478
青春惊慌失措
青春惊慌失措 2021-01-05 07:22

I start a timer in an Angular 2 component which is inside a router outlet.

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

When I leave the route

3条回答
  •  一生所求
    2021-01-05 07:57

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

提交回复
热议问题