我在路由器插座內的Angular 2組件中啓動計時器。Angular 2中的路由更改時的結束時間間隔
setInterval(() => {
...
}, 10000);
當我離開嵌入組件的路由時,計時器不會退出。我怎樣才能做到這一點?
我在路由器插座內的Angular 2組件中啓動計時器。Angular 2中的路由更改時的結束時間間隔
setInterval(() => {
...
}, 10000);
當我離開嵌入組件的路由時,計時器不會退出。我怎樣才能做到這一點?
這應做到:
routerOnActivate() {
this.timer = setInterval(()=>{
...
}, 10000);
}
routerOnDeactivate() {
clearInterval(this.timer);
}
你可以清除從該掛鉤的間隔。礦井由組件/視圖控制。
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);
}
}
也許你想要的東西是從angular2/router
更好OnDeactivate
(也許還OnActivate
取決於你的用例),因爲你說你要當用戶離開的路線。如果我理解正確的話來結束計時器。
export Compnent implements OnInit, OnDeactivate {
private timer;
ngOnInit(){
this.timer = setInterval(_ => {
// disco
}, 10000);
}
routerOnDeactivate() {
clearInterval(this.timer);
}
}