数组中的映射不适用于ngOnChange事件Angular 5

时间:2018-01-27 16:50:35

标签: javascript arrays angular

我是Angular的新手,这是我的第一款应用。我有一个父组件,它使用服务从API获取数据。通过服务的响应,我创建了一个数组并将其作为属性传递给子组件。在子组件中,我有以下ngOnChange事件

ngOnChanges(changes: any) {
    console.log("Mode total in mode", this.modeTotal);
    this.modeTotal.map(mode => {
      console.log("For each");
      this.doughnutChartLabels.push(mode.name);
      this.doughnutChartData.push(mode.total);
      console.log(`Loop inside onChange Name: ${mode.name} and Total: ${mode.total}`);
    });
    console.log("DoughnutChartLabels", this.doughnutChartLabels);
    console.log("DoughnutChartData", this.doughnutChartData);
}

我面临的问题是地图功能上方和下方的控制台正在运行,打印 modeTotal doughnutChartLabels doughnutChartData 的内容但不是map函数中的字符串。并且modeTotal具有我希望返回的数据数组。

我错过了什么?

注意:我将数据从另一个从API接收数据的组件推送到modeTotal。即使将新数据推入其中,modeTotal也不会更新。

1 个答案:

答案 0 :(得分:1)

The change event will not occur on an array when a new data is pushed into it since the variable is referring to the same object. Try adding a local variable to monitor the push changes.