Angular 2/4中TypeScript数组内容未更新

3

我在 Angular 组件中更新数组内容时遇到了问题。

名为 arr 的数组被创建来存储由 ChartJS 图表数据集使用的值。

ngOnInit 中,我运行 retrieveTempDataReturn() 函数,该函数从数据服务返回一个检索到的值数组 _arr,并将其分配给我在顶部声明的 arr 数组。

页面加载后,我运行 displayArray() 函数,该函数使用按钮上的点击事件显示 arr 数组的内容。浏览器控制台的输出如下:

Array contents: 22.1,22.1,23.1,24.1,25.1,26.1,25.1,24.1,22.1,21.1 

因此,我可以看到检索到的数据已成功更新到 arr 数组中。
然后,我使用按钮的点击事件运行另一个函数 retrieveHumidDataAssign(),该函数从同一数据服务中检索另一组数据并立即将数据分配给 arr 数组。稍后在函数中,我通过 console.log() 打印出 arr 数组的内容,并且我可以看到 arr 数组中的值已更新。浏览器控制台的输出如下:
Array assigned Humid: 56,56,56,56,56,56,56,56,56,56

但是当我再次使用displayArray()函数来查看arr数组中的内容时,该内容仍然是最初的内容。在浏览器控制台中的输出如下:

Array contents: 22.1,22.1,23.1,24.1,25.1,26.1,25.1,24.1,22.1,21.1

retrieveHumidDataAssign()函数中console.log打印出来的arr数组内容看起来已经被改变。但是,当我单独运行另一个函数来显示它的内容时,它却没有改变。

为什么会发生这种情况?如何更新数组中的内容?请帮帮我。

以下是组件文件:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import {BaseChartDirective} from 'ng2-charts/ng2-charts';

@Component({
  templateUrl: 'chartjs.component.html'
})
export class ChartJSComponent {

  arr = [];

  constructor(private dataService: DataService){
  }

  ngOnInit(){
    this.arr = this.retrieveTempDataReturn();
  }

//function that retrieves and returns array of temperature values
  retrieveTempDataReturn(){
    var _arr = new Array();
    this.dataService.getData().subscribe(function(response){
      console.log("Response: " + JSON.stringify(response));
      for(var item of response){
        console.log("Pushing " + item.Temperature);
        _arr.push(item.Temperature);
      }
      console.log("Array returned: " + _arr);
    });
    return _arr;
  }

//function that retrieves and assign array into the "arr" array
  retrieveHumidDataAssign(){
    var _arr = new Array();
    this.dataService.getData().subscribe(function(response){
      console.log("Response: " + JSON.stringify(response));
      for(var item of response){
        _arr.push(item.Humidity);
      }
      this.arr = _arr;
      console.log("Array assigned Humid: " + this.arr);
    });
  }

//display the data on the chart by using "arr" array in the dataset for the chart
  refreshChart(){
    console.log("To display: " + this.arr);
    this.datasets = [{
      label: "Values",
      data: this.arr 
    }];
  }

//function to display the contents of the array
  displayArray(){
    console.log("Array contents: " + this.arr);
  }

//arrays that are used by Chart JS chart for data visualization
  private datasets = [
    {
      label: "Values",
      data: []
    }
  ];

  private labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'];

  private options = {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  };

}

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­


你在哪里以及如何调用了函数 displayArrayretrieveHumidDataAssign - Pengyy
我通过在 .html 上使用 click 事件的按钮调用该函数。 - Wei Minn
我通过在 .html 上使用 click 事件调用它们各自的按钮来调用这些函数。例如, <button (click)="retrieveHumidDataAssign()">检索湿度数据</button> <button (click)="displayArray()">显示数组</button> - Wei Minn
1个回答

3

在使用回调函数时,需要保持上下文并使用 this,否则this会变成回调函数本身。

这里可以使用 箭头函数

//function that retrieves and assign array into the "arr" array
retrieveHumidDataAssign(){
  var _arr = new Array();
  this.dataService.getData().subscribe(response => {     // <----arrow function here
    ...
    this.arr = _arr;
    console.log("Array assigned Humid: " + this.arr);
  });
}

哇塞!!!非常感谢!问题解决了!但是 function(response) {} 和 response => {} 有什么区别呢?我以为它们是一样的? - Wei Minn
@KelvinWeiMinn 在回调函数中使用 this 会发生变化,你可以通过在回调函数中使用 console.log(this) 来确认。而使用箭头函数则可以保留原始上下文。 - Pengyy
谢谢!谢谢!你救了我的命! - Wei Minn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接