2016-02-22 78 views

回答

7

這應做到:

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

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

你可以清除從該掛鉤的間隔。礦井由組件/視圖控制。

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

也許你想要的東西是從angular2/router更好OnDeactivate(也許還OnActivate取決於你的用例),因爲你說你要當用戶離開的路線。如果我理解正確的話來結束計時器。

export Compnent implements OnInit, OnDeactivate { 
    private timer; 

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

    routerOnDeactivate() { 
     clearInterval(this.timer); 
    } 
} 
相關問題