Angular ngFor更新数组时不更新DOM

Ale*_*rds 5 angular

我正在使用Angular,并且在通过数据将数据显示到DOM时遇到问题ngFor

默认情况下,dataArray我的代码中的变量为空,但是对给定端点的HTTP发布请求将更新该数组,并使用对象集合填充该数组。

我可以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);
    })
  }

}
Run Code Online (Sandbox Code Playgroud)

角度模板

<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>
Run Code Online (Sandbox Code Playgroud)

谢谢!

Fat*_*med 2

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;
  });
Run Code Online (Sandbox Code Playgroud)

在你看来

<li *ngFor="let item of (dataArray | async)">
  {{ item }}
</li>
Run Code Online (Sandbox Code Playgroud)