[英]While using setInterval to load a list in angular 4 the same loadlist function firing when clicking other links also
[英]setInterval function is running in other components also in Angular 6
我是Angular的新手(6)。 我在組件中使用setInterval
函數。 它正在工作但是當我導航到另一個路由時, setInterval
繼續執行。 請幫我確定一下原因。
//Calling it in ngOnit()
autosavedraftsolution() {
setInterval(() => {
console.log(this.draftSolutionForm);
if (this.solutionTitleValid) {
this.savedraftsolution();
}
}, this.autoSaveInterval);
}
//savedraftsolution()
savedraftsolution() {
console.log("saving..");
this.connectService.saveDraftSolution({
Title: this.draftSolutionForm.get('Title').value,
Product: this.draftSolutionForm.get('Product').value
} as Draftsolution).subscribe(draftsol => {
console.log("saved");
});
}
它一直在控制台中顯示“保存...”和“已保存”消息。
組件卸載時,需要調用clearInterval
來停止它:
this.intervalId = setInterval(...);
卸載組件時:
ngOnDestroy() {
clearInterval(this.intervalId);
}
多米尼克是對的。 您必須清除組件被銷毀時的間隔。 你可以做這樣的事情
ngOnInit(){
this.saveInterval = setInterval(() => {}, 1000)
}
ngOnDestroy(){
clearInterval(this.saveInterval)
}
確保您的組件實現OnInit和OnDestroy。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.