setInterval 函数也在 Angular 6 中的其他组件中运行

eml*_*les 1 javascript setinterval angular angular6

我是 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");

    });
  }
Run Code Online (Sandbox Code Playgroud)

它不断在控制台中向我显示“正在保存..”和“已保存”消息。

Dom*_*nic 5

clearInterval当组件卸载时,您需要调用来停止它:

this.intervalId = setInterval(...);
Run Code Online (Sandbox Code Playgroud)

当您的组件卸载时:

ngOnDestroy() {
  clearInterval(this.intervalId);
}
Run Code Online (Sandbox Code Playgroud)