typescript Angular 2 中路由更改时的结束间隔
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35561320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
End interval when route changes in Angular 2
提问by daniel
I start a timer in an Angular 2 component which is inside a router outlet.
我在路由器插座内的 Angular 2 组件中启动了一个计时器。
setInterval(() => {
...
}, 10000);
When I leave the route in which the component is embedded the timer isn't quit. How can I achieve that?
当我离开嵌入组件的路线时,计时器不会退出。我怎样才能做到这一点?
回答by inoabrian
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);
}
}
回答by Sasxa
This should do it:
这应该这样做:
routerOnActivate() {
this.timer = setInterval(()=>{
...
}, 10000);
}
routerOnDeactivate() {
clearInterval(this.timer);
}
回答by martin
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.
也许你想要的是更好OnDeactivate
的angular2/router
(也许还OnActivate
取决于你的用例),因为你说你要结束的时候,用户离开的路线。如果我的理解是正确的计时器。
export Compnent implements OnInit, OnDeactivate {
private timer;
ngOnInit(){
this.timer = setInterval(_ => {
// disco
}, 10000);
}
routerOnDeactivate() {
clearInterval(this.timer);
}
}