我的应用程序中有一个进度条,它使用 while 循环进行更新。我可以在每个循环中成功更改更新进度值,但 View 仅在整个 while 循环完成后更新。有没有什么办法可以在 while 循环中添加一些东西,比如在每个循环上添加“ForceViewUpdate()”之类的东西?
在此处检查我的示例并打开控制台以查看正在更新的值: https://stackblitz.com/edit/angular-5zlja4?file=app%2Fapp.component.ts
最佳答案
您等待的方式会阻塞整个 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);
});
}
}
关于javascript - While 循环中的 Angular 5 更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49899517/