在 ngOnInit 中,我創建了填充 items 陣列:
id: string = '';
items: Item[] = [];
ngOnInit(): void {
this.id = this.activatedRoute.snapshot.params['id'];
this.itemService.getItems(this.id).subscribe({
next: (res) => this.items = res
})
到目前為止一切順利,我得到了 items 陣列。現在通過使用 *ngFor = "let item of items" 我可以在 HTML 頁面中列印出 {{item.color}} 串列。這意味著我已經填滿了 items 陣列。
接下來,我想將每個 item.color 推入一個單獨的陣列中。所以在同一個 ngOnInit 方法中,我繼續這樣:
let colorArray:string[] = [];
for (let item of this.items) {
colorArray.push(item.color)
}
在同一個 ngOnInit 方法中,我通過控制臺記錄它:
console.log(colorArray);
但是,它回傳了一個空陣列。什么地方出了錯?
uj5u.com熱心網友回復:
這將是一個時間問題 - 陣列試圖在資料可用之前被填充。
我會重構以在結果回傳時映射一個新陣列 - 這樣在回傳結果時它總是會被填充。
id: string = '';
items: Item[] = [];
colorArray:string[] = [];
ngOnInit(): void {
this.id = this.activatedRoute.snapshot.params['id'];
this.itemService.getItems(this.id).subscribe({
next: (res) => {
this.items = res;
this.colorArray = res.map(r => r.color);
}
})
}
uj5u.com熱心網友回復:
setTimeout(()=>{
let colorArray:string[] = [];
for (let item of this.items) {
colorArray.push(item.color)
}
},1000)
這是一個與佇列和堆疊之間的差異有關的時間問題,第二個函式也是同步的,這意味著它在第一個函式之前回傳結果,必須等待后端回應訂閱然后回傳值。您也可以利用角度生命周期鉤子,但第二個在 ngAfterViewInit 或 ngDoCheck
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/510207.html
標籤:有角度的打字稿
