[英]Angular ngFor not updating DOM when array is updated
我正在使用 Angular,並且在通過ngFor
向 DOM 顯示數據時遇到問題。
默認情況下,我的代碼中的dataArray
變量為空,但對給定端點的 HTTP post 請求會更新該數組,並使用一組對象填充該數組。
我能夠對數組進行console.log()
並查看新更新的值。 但是, ngFor
似乎仍然沒有遍歷更新后的數組並相應地修改 DOM。
我還可以在我的代碼中使用項目定義數組,並且ngFor
將正確迭代並顯示值。
據我所知,DOM 應該根據組件中呈現的狀態進行更新,但我可能遺漏了一些東西。
這是我的代碼。
打字稿
import { Component, OnInit } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Component({
selector: "app-data-item",
templateUrl: "./data-item.component.html",
styleUrls: ["./data-item.component.css"]
})
export class DataItemComponent implements OnInit {
public dataArray: Array<object> = [];
//Using ngFor to iterate through this array would work w/ no problem.
anotherArray: Array<String> = ["Hello", "there"];
constructor(private http: HttpClient) {}
ngOnInit() {}
//A call is made to sendRequest from an outside component, which is able to successfully trigger this function
sendRequest(requestBody: object) {
this.http
.post("http://localhost:4343/getProgramDetails", requestBody, {
headers: { "Content-Type": "application/json" }
})
.subscribe(response => {
const dataItems = response[0]["key"];
dataItems.forEach(item => {
//Push an itemInstance to the dataArray variable
const itemInstance = {
description: item["description"],
type: incentive["type"],
value: incentive["value"]
};
this.dataArray.push(itemInstance);
});
//Am able to see array values here
console.log(this.dataArray);
});
}
}
角度模板
<table>
<tr>
<td>Vehicle</td>
<td>Incentive Type</td>
<td>Amount</td>
</tr>
<ul>
<!-- Items won't print here when array is updated -->
<li *ngFor="let item of dataArray">
{{ item }}
</li>
</ul>
</table>
謝謝!
this.dataArray = this.http
.post("http://localhost:4343/getProgramDetails", requestBody, {
headers: { "Content-Type": "application/json" }
})
.map(response => {
let result = [];
const dataItems = response[0]["key"];
dataItems.forEach(item => {
//Push an itemInstance to the dataArray variable
const itemInstance = {
description: item["description"],
type: incentive["type"],
value: incentive["value"]
};
result.push(itemInstance);
});
return result;
});
在你看來
<li *ngFor="let item of (dataArray | async)">
{{ item }}
</li>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.