我的应用程序中有一个进度条,它使用while循环进行更新。我可以用每个循环成功地更改更新进度值,但是视图只有在整个while循环完成后才会更新。有没有任何方法在while循环中添加类似于每个循环的"ForceViewUpdate()“,或者类似的东西?
在这里检查我的示例并打开控制台,查看正在更新的值:https://stackblitz.com/edit/angular-5zlja4?file=app%2Fapp.component.ts
发布于 2018-04-18 12:22:45
等待的方式阻止了整个jsvascript线程。Javascript运行在单个线程上,如果阻止运行while循环的线程,则不允许执行任何其他代码,包括UI更新。您应该使用setTimeout来在一段时间后运行代码,或者,您可以使用aync/await和Promises来给您的代码一个更有顺序的感觉:
export class AppComponent {
sStatus = "Inactive";
iProgressMax = 100;
iProgressValue = 0;
async Run() {
this.sStatus = "Running...";
while (this.iProgressValue < this.iProgressMax) {
await this.wait(1000);
this.iProgressValue = this.iProgressValue + 20;
console.log(this.iProgressValue);
}
this.sStatus = "Complete";
}
wait(ms: number) {
return new Promise((resolve)=> {
setTimeout(resolve, ms);
});
}
}https://stackoverflow.com/questions/49899517
复制相似问题