我正在構建一個 Angular 應用程式,我試圖在字串陣列的每個 forEach 迭代中插入一個字串的值。(quotesData 是我從中獲取值的字串陣列)
我的功能是這樣的:
export() {
this.quotesData.forEach(element => {
this.quote = element;
this.wait(1000); \\ <- manually written function to postpone next line execution for 1s
console.log(this.quote);
});
}
問題是 {{quote}} 的 HTML 插值值直到最后一次迭代結束才會更新。但是,每次迭代后, this.quote 的值都會正確更新并顯示在控制臺和除錯器中。
uj5u.com熱心網友回復:
我不確定你的等待函式是如何實作的,但我猜它仍然是異步運行的。為了解決它,我建議將時間增加到 5000 并檢查值是否立即顯示在控制臺中。
否則,這是一個使用 async await 的作業示例:
import { Component } from '@angular/core';
@Component({
selector: 'hello',
template: `<button (click)="display()" >Display</button><h1>Hello {{quote}}!</h1>`,
})
export class HelloComponent {
quotesData: Array<string> = ['A', 'B', 'C'];
quote: string = '';
wait(ms) {
return new Promise((res) => setTimeout(res, ms));
}
async display() {
for (let quote of this.quotesData) {
this.quote = quote;
await this.wait(1000);
console.log(this.quote);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/385191.html
標籤:javascript html 有角的 打字稿
