我正在使用Angular,我遇到了通过ngFor
向DOM显示数据的问题。
默认情况下,我的代码中的dataArray
变量为空,但是给定端点的HTTP post请求会更新数组,并使用一组对象填充数组。
我能够console.log()
数组并查看新更新的值。但是,ngFor
似乎仍然没有迭代更新的数组并相应地修改DOM。
我也可以在我的代码中使用项目定义数组,ngFor
将正确迭代并显示值。
根据我的理解,DOM应该根据组件中显示的状态进行更新,但我可能遗漏了一些东西。
这是我的代码。
的JavaScript
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>
谢谢!
答案 0 :(得分:0)
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>