我在 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
}
}]
}
};
}
displayArray
和retrieveHumidDataAssign
? - Pengyy<button (click)="retrieveHumidDataAssign()">检索湿度数据</button> <button (click)="displayArray()">显示数组</button>
- Wei Minn