var activeArr = [];
var activeDate = [];
var day = (endDate - startDate) / (24 * 60 * 60 * 1000);
for (var i = 1; i < day + 1; i++) {
activeDate.push(endDate - (24 * 60 * 60 * 1000) * i);
var start = endDate - (24 * 60 * 60 * 1000) * i;
var end = endDate - (24 * 60 * 60 * 1000) * (i - 1);
statisService.getRegStatis(start, end).then(function(response) {
console.log(response.data.data); //can get data
activeArr.push(response.data.data)
});
}
console.log(activeArr); //nothing in the array
console.log(activeDate); // can push data into this array
服务:
userServiceModule.factory('statisService', ['$http','serverUrl', function($http,serverUrl){
return {
getRegStatis: function(startDate,endDate){
var url = serverUrl +"/adminDA/dbReport?startTime="+startDate+"&endTime="+endDate;
return $http.get(url);
}
};
}])
答案 0 :(得分:3)
首先改变你的工厂:
userServiceModule.factory('statisService', ['$http','serverUrl', function($http,serverUrl){
return {
getRegStatis: function(startDate,endDate){
var url = serverUrl +"/adminDA/dbReport?startTime="+startDate+"&endTime="+endDate;
return $http.get(url).then(function(result){
return result.data;
});
}
};
}])
然后在控制器中:
var activeArr = [];
var activeDate = [];
var day = (endDate - startDate) / (24 * 60 * 60 * 1000);
for (var i = 1; i < day + 1; i++) {
activeDate.push(endDate - (24 * 60 * 60 * 1000) * i);
var start = endDate - (24 * 60 * 60 * 1000) * i;
var end = endDate - (24 * 60 * 60 * 1000) * (i - 1);
statisService.getRegStatis(start, end).then(function(data) {
console.log(data); //can get data
activeArr.push(data);
console.log(activeArr); //only now you can log activeArr because you have to wait for promise
});
}
console.log(activeDate);
$ http确实会返回一个承诺,但您需要使用.then或.success
从工厂函数返回它答案 1 :(得分:3)
问题是您是在解析promise之前记录数组,更新代码以在更新.then
数组后记录callback
activeArr
内的数组值/ p>
var activeArr = [];
var activeDate = [];
var day = (endDate - startDate) / (24 * 60 * 60 * 1000);
for (var i = 1; i < day + 1; i++) {
activeDate.push(endDate - (24 * 60 * 60 * 1000) * i);
var start = endDate - (24 * 60 * 60 * 1000) * i;
var end = endDate - (24 * 60 * 60 * 1000) * (i - 1);
statisService.getRegStatis(start, end).then(function(response) {
console.log(response.data.data); //can get data
activeArr.push(response.data.data)
console.log(activeArr); //now your array will be populated
});
}
console.log(activeDate); // can push data into this array
答案 2 :(得分:1)
$ http会返回一个承诺 - 而不是数据。你应该在$ http电话
之后应用一个回调$http.get('address').success(function(res) {
//var res is the data sent back from the request..
// in your case it should look like
return res;
});