簡體   English   中英

我正在使用 setTimeout() 調用刷新 function,但是當我移動到另一個組件時它不會停止調用刷新?

[英]I am using setTimeout() to call a refresh function, but it doesnt stop calling refresh when I move to another component?

我是 angular 的新手,我有一個 function,刷新,我需要在每 1 分鍾后調用一次,但是當我進入該組件時它工作正常,當我導航到其他視圖時,它仍在調用刷新 ZC1C125268D18A94, refresh function 在 ngOnInit() 中調用,然后這個 setTimeout() function 我只在 refresh() function 中創建。

ngOnInit(){
 this.refresh();
 }
 ...
 ...

refresh(){
...
...

setTimeout(() => {
  this.refresh();
   },10000) 
 }

您應該使用setInterval而不是setTimeout並且在 ngOnDestroy 中您需要使用clearInterval

this.timer = setInterval(() => {
   this.refresh();
}, 10000);

清除間隔

ngOnDestroy(){
  clearInterval(this.timer);
}

您可以再創建一個屬性,例如timeout並像這樣更新您的 class,

ngOnInit(){
 this.refresh();
 }
 ...
 ...
timeout;
refresh(){
...
...

this.timeout = setTimeout(() => {
  this.refresh();
   },10000) 
 }
ngOnDestroy(){
  clearTimeout(this.timeout);
}

除了OnInit之外,您的 class 還必須為此實現OnDestroy接口。

盡管對於您的用例, setInterval更有意義,您也可以制作像IntervalService這樣的可重用服務來封裝整個行為。

setInterval 位:-

interval;

ngOnInit()
{
this.interval = setInterval(() => {
   this.refresh();
}, 10000);
}
ngOnDestroy(){
  clearInterval(this.interval);
}

refresh(){....}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM