这是我的代码:
function getLineGraphData(unit, startTs, endTs, startState, endState){
points = [];
console.log('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+endState);
$http.get('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+endState).success(function(data){
for (var i = 0; i < data.length; i++) {
points.push({x:getBasicTimeFromEpoch(data[i].ts), y:data[i].data});
}
return points;
});
}
function fileStateLineGraph(unit, startTs, endTs){
getLineGraphData(unit, startTs, endTs, 1, 2);
console.log(getLineGraphData(unit, startTs, endTs, 1, 2));
var dp1= getLineGraphData(unit, startTs, endTs, 1, 2);
var dp2= getLineGraphData(unit, startTs, endTs, 2,3);
var dp3 = getLineGraphData(unit, startTs, endTs, 3,4);
console.log(dp1);
console.log(dp2);
console.log(dp3);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Click on legend items to hide/unhide dataseries"
},
legend: {
cursor: "pointer",
itemclick: function (e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
},
data: [{
//axisYType:"secondary",
showInLegend: true,
type: "line",
dataPoints: dp1
}, {
showInLegend: true,
type: "line",
dataPoints: dp2
}, {
showInLegend: true,
type: "line",
dataPoints: dp3
}]
});
chart.render();
}
fileStateLineGraph("day",1404000000, 1406000000)
当我运行console.logs时,只显示&#34; undefined。&#34;我想知道是否因为函数在JSON调用完成之前运行,但我从未遇到过这样的错误。
答案 0 :(得分:1)
首先,您的getLineGraphData
函数没有返回值。其次,它是异步运行的,因此您必须等待success
处理程序才能访问points
数据。
首先,您必须添加return
语句:return $http.get(...
。这将返回一个承诺。
其次,要访问points
,您必须使用promise.then(function(points) { ... })
。在then
函数中,您可以访问数据。
现在,如果您依赖多组积分,则必须等待所有积分完成。 You can use $q.all(...)
as follows:
$q.all({
dp1: getLineGraphData(unit, startTs, endTs, 1,2),
dp2: getLineGraphData(unit, startTs, endTs, 2,3),
dp3: getLineGraphData(unit, startTs, endTs, 3,4)
}).then(function(dataPoints) {
var dp1 = dataPoints.dp1, dp2 = dataPoints.dp2, dp3 = dataPoints.dp3;
... Create your chart ...
});
答案 1 :(得分:1)
- 您从$ http.get的成功回调中返回点数。这并不意味着它是从getLineGraphData返回的。 $ http.get返回一个promise,这是你应该从函数返回的。然后在promise上成功回调并填充dp1等等..
function getLineGraphData(unit, startTs, endTs, startState, endState){
points = [];
console.log('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+endState);
return $http.get('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+endState);
}
var dp1 = [];
getLineGraphData(unit, startTs, endTs, 1, 2).success(function(data){
for (var i = 0; i < data.length; i++) {
dp1.push({x:getBasicTimeFromEpoch(data[i].ts), y:data[i].data});
}
console.log(dp1);
});
dp1应打印好。