在Angular中使用setInterval时,需要使用NgZone来确保代码在Angular的变更检测周期中被检测到。以下是使用NgZone解决setInterval问题的示例代码:
import { Component, NgZone } from '@angular/core';
@Component({
selector: 'app-component',
template:
})
export class AppComponent {
count = 10;
constructor(private ngZone: NgZone) {}
ngOnInit() { setInterval(() => { this.ngZone.run(() => { this.count--; }); }, 1000); } }
在上面的代码中,我们注入了NgZone并在构造函数中声明它。然后在ngOnInit函数中,我们使用setInterval函数来启动一个定时器,并在其中使用ngZone.run方法将代码包装在Angular的变更检测周期中。这确保了Angular会检测到定时器里的变化并进行更新。