我在Angular 9代码中有一个导航栏组件,在该组件中,用户可以看到带有其会话时间的倒数计时器。每秒钟都会倒数。
我的组件看起来像这样:
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.scss']
})
export class NavComponent implements OnInit, OnDestroy {
timer: any;
countdownTimer = '';
constructor() { }
ngOnInit() {
this.startTimer();
}
ngOnDestroy() {
this.stopTimer();
}
startTimer() {
this.timer = setInterval(() => {
this.countdownTimer = this.milisecondsToTime(3600000);
}, 1000);
}
milisecondsToTime(duration: number): string {
const seconds = Math.floor((duration / 1000) % 60);
const minutes = Math.floor((duration / (1000 * 60)) % 60);
const hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
const hoursString = (hours < 10) ? '0' + hours : hours;
const minutesString = (minutes < 10) ? '0' + minutes : minutes;
const secondsString = (seconds < 10) ? '0' + seconds : seconds;
return hoursString + ':' + minutesString + ':' + secondsString;
}
stopTimer() {
clearTimeout(this.timer);
}
在nav.component.html中:
<div>
Session: {{ countdownTimer }}
</div>
此代码每秒钟发生一次事件冒泡,并且在我所有的代码中,一次又一次地运行函数。代码库变得足够大,并且此事件冒泡使所有软件变慢。
是否有更好的方法或最佳实践来显示倒数计时器,而不是每隔一秒钟就使Angular充满事件?
我在上面使用您的代码不会启动倒数,我不确定3600000的含义是什么,我认为这是倒数的持续时间,也许吗?我创建了一个示例,不确定它是否是您要寻找的解决方案。
使用Angular 9,您可以设置新属性ngZoneEventCoalescing
以防止事件冒泡。您需要在bootstrapModule
方法中添加它。
示例
platformBrowserDynamic()
.bootstrapModule(AppModule, { ngZoneEventCoalescing: true })
.catch(err => console.error(err));
您可以阅读有关此here的更多信息