我有这个 Angular 组件文件
export class MyComponent implements OnInit {
updateValue() {
// getting api data from the backend
}
ngOninit() {
setInterval(()=>{
this.updateValue()
}, 5000)
}
}
现在这里发生了什么,当我导航到不同的组件时,我的 setinterval
继续运行并从后端获取数据。有没有解决这个问题的解决方案或以这种方式进行 Angular 工作。我希望当我导航到其他组件时,setInterval 应该自动停止。
另外 - 我正在从子组件导航到父组件
即来自 /home/dashboard ----->/home
最佳答案
保留对 this.interval
的引用,并使用 ngOnDestroy
处理程序在用户通过 clearInterval
导航离开时停止间隔。
https://angular.io/api/core/OnDestroy
https://angular.io/guide/lifecycle-hooks
ngOnInit() {
this.interval = setInterval(() => {
this.updateValue()
}, 5000)
}
ngOnDestroy() {
if (this.interval) {
clearInterval(this.interval);
}
}
关于javascript - 通过路由更改组件时,函数调用永不停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58158245/