我刚接触angular,并且我有一个名为refresh的函数,我每隔1分钟就需要调用它,但是当我进入该组件时,它工作得很好,当我导航到其他视图时,它仍然在调用refresh函数,refresh函数在ngOnInit()中被调用,然后我在refresh()函数中创建了这个setTimeout()函数。
ngOnInit(){
this.refresh();
}
...
...
refresh(){
...
...
setTimeout(() => {
this.refresh();
},10000)
}发布于 2021-02-04 14:12:43
您可以再创建一个像timeout这样的属性,并像这样更新您的类,
ngOnInit(){
this.refresh();
}
...
...
timeout;
refresh(){
...
...
this.timeout = setTimeout(() => {
this.refresh();
},10000)
}ngOnDestroy(){
clearTimeout(this.timeout);
}除了OnInit之外,您的类还必须为此实现OnDestroy接口。
尽管对于你的用例来说,setInterval更有意义,而且你也可以像IntervalService一样做一个可重用的服务来封装整个行为。
setInterval位:-
interval;
ngOnInit()
{
this.interval = setInterval(() => {
this.refresh();
}, 10000);
}
ngOnDestroy(){
clearInterval(this.interval);
}
refresh(){....}发布于 2021-02-04 14:27:41
您应该使用setInterval而不是setTimeout,并且在ngOnDestroy中需要使用clearInterval
this.timer = setInterval(() => {
this.refresh();
}, 10000);清除间隔
ngOnDestroy(){
clearInterval(this.timer);
}https://stackoverflow.com/questions/66040164
复制相似问题