我是javascript新手,以前仅使用过Python编程语言。我正在使用Express / Node JS开发Web应用程序,并具有以下代码,以使用Chart js库呈现图表:
app.controller("ambientCtrl", function($scope, $http, $window, $timeout) {
$scope.sensors = []
$http.get('https://cors-anywhere.herokuapp.com/https://cararobot.eu/api/sensor?time_from=1550049008.4456067&time_to=1550052056.438995', {dataType: 'json'}).then(function successCallback(response) {
var ctx = document.getElementById("myChart").getContext('2d');
var colors = ["rgba(255,99,132,1)","rgba(54, 162, 235, 1)","rgba(255, 206, 86, 1)","rgba(75, 192, 192, 1)","rgba(153, 102, 255, 1)"];
var unique_timestamps = [...new Set(response.data.map(item => item.timestamp))].sort(function(a, b){return a-b});
//console.log(Object.keys(unique_timestamps).length)
var sensor_list = [...new Set(response.data.map(item => item.sensor_id))].sort(function(a, b){return a-b});
$scope.sensors = sensor_list;
var temperature_datasets = []; // Will hold final arrays of sensor readings
for (i = 0; i < sensor_list.length; i++) {
readings_arr =[]; // Holds the array of temperatures for one sensor
for (j = 0; j < unique_timestamps.length; j++) {
var result = response.data.filter(obj => {
return (obj.timestamp === unique_timestamps[j] && obj.sensor_id === sensor_list[i])
})
if (typeof result[0] !== 'undefined') {
readings_arr[j]=result[0].temp;
} else {
readings_arr[j]="";
}
}
temperature_datasets[i] = readings_arr;
var series = {data:temperature_datasets[i],label:sensor_list[i],
fill: false,
backgroundColor: colors[i],
borderColor: colors[i], // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "black",
pointBackgroundColor: "white",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: true,
}
$scope.chart_dataset.push(series);
}
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: unique_timestamps,
datasets: $scope.chart_dataset
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
console.log(myChart.data);
}, function errorCallback(response) {
console.log("HANDLE ERROR");
});
console.log(myChart.data);
});
我遇到的问题是,运行请求后,我需要访问myChart.data。因此,第66行的'console.log(myChart.data)'在第72行未定义。类似地,当我尝试从请求内部将全局变量'sensors'设置为'sensor_list'时,在以后使用它,它也是未定义的。我知道这是由于javascript的异步特性引起的,但是我在努力使用回调方法来解决问题。我应该只将http请求添加到回调函数中,然后将响应数据另存为变量吗?