在组件销毁时,应该取消相关的定时器。可以在Angular生命周期钩子函数ngOnDestroy()中取消定时器。
示例代码:
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({ selector: 'app-timer', templateUrl: './timer.component.html', styleUrls: ['./timer.component.css'] }) export class TimerComponent implements OnInit, OnDestroy {
timer: any; count: number = 0;
constructor() { }
ngOnInit() { this.timer = setInterval(() => { this.count++; }, 1000); }
ngOnDestroy() { clearInterval(this.timer); }
}
上一篇:Angular地理定位