我想在我的Angular组件中定期重复一个任务。我的第一次尝试是在构造函数中使用这样的setInterval构造。问题是,当我隐藏组件时,执行不会停止,当我显示它时,它甚至执行2x。那么,在显示组件时执行任务的正确方法是什么(如果组件列表不再显示则停止)?
// in constructor of component
setInterval(() => {
// do something
}, intervall * 1000);
subscription : Subscription ;
ngOnInit()
{
const observbles = new Observable(sub => {
//do something.
this.subscription = observbles.subscribe(x => ....);
});
}
ngOnDestroy()
{
this.subscription.unsubscribe();
}
NOTE : Do your actions in ngOnInit() and to end it implement it
in ngOnDestroy()
它将重复该任务,直到您进入该组件和当您离开我所展示的演示组件时,将其销毁可见
基于Vegas的答案(再次感谢!)我是这样解决的:
myIntervall = null;
ngOnInit() {
this.myIntervall = setInterval(() => {
console.log(
'I am called every two seconds as long as this component is shown'
);
}, 2 * 1000);
}
ngOnDestroy() {
clearInterval(this.myIntervall);
}
使用定时器,您可以在ngOnInit
和ngOnDestroy
中订阅和取消订阅。
export class MyComponent implements OnInit, OnDestroy {
interval = 5;
timerSub!: Subscription;
ngOnInit() {
this.timerSub = timer(0, this.interval * 1000).subscribe();
}
ngOnDestroy() {
this.timerSub.unsubscribe();
}
}