[英]refreshing data on page every X seconds for angular component
我需要每 30 秒刷新一次角度組件的數據。 我使用簡單的setInterval
:
this.interval = setInterval(() => {
this.refresh(); // api call
}, 10000);
但是,這是不正確的,因為即使我導航到另一個“頁面”(在 Angular SPA 中,所有內容都是一頁,因此它實際上不是另一頁),每 30 秒刷新一次。
僅在特定頁面/組件上每 30 秒刷新一次數據的正確方法是什么?
您可以在組件的OnDestroy
生命周期掛鈎上銷毀時間間隔。
使用clearInterval(this.interval)
ngOnDestroy() {
if (this.interval) {
clearInterval(this.interval);
}
}
您可以在組件的ngOnDestroy
生命周期鈎子中ngOnDestroy
ngOnDestroy() {
clearInterval(this.interval);
}
ngOnDestroy
將在摘要循環中每次銷毀組件時調用,它也會清除您的間隔(如果您這樣做)。 通常用於在當前路線導航到另一個之后調用我們不需要的邏輯。
嘗試這個。
routerOnActivate() {
this.interval = setInterval(() => {
this.refresh(); // api call
}, 10000);
}
routerOnDeactivate() {
clearInterval(this.interval);
}
當您導航到另一個頁面時,您必須清除您設置的間隔。
this.interval = setInterval(()=>{
...
});
navigateToAnotherPage = () => {
//function to navigate to another page
clearInterval(this.interval);
router.navigate(...)//if you are using router to navigate
}
嘗試這個。
save: boolean = false;
autoSave() {
setInterval(() => {
console.log('setTimeOut');
this.save = true;
}, 1000);
}
您還可以利用反應式風格。
import { timer } from 'rxjs';
/*
timer takes a second argument, how often to emit subsequent values
in this case we will emit first value after 1 second and subsequent
values every 2 seconds after
*/
const source = timer(0, 2000);
//output: 0,1,2,3,4,5......
const subscribe = source.subscribe(val => console.log(val));
參考 - https://www.learnrxjs.io/learn-rxjs/operators/creation/timer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.