我尝试在完成foreach循环后得到所有数据但不知何故总是得到[]
$scope.temp = [];
angular.forEach(seasonStageIds, function (seasonStageId, index) {
playerService.getPlayerProfile(seasonStageId, $stateParams.params.playerSename).then(function (data) {
playerService.getPlayerPositionPerSeason(seasonStageId, data.data.Id).then(function (data) {
console.log(data);
_.chain(data)
.groupBy('Position')
.map(function (value, key) {
var goals = _.reduce(value, function (memo, num) {
return memo + num.Goals;
}, 0);
var apps = _.reduce(value, function (memo, num) {
return memo + num.Apps;
}, 0);
var assists = _.reduce(value, function (memo, num) {
return memo + num.Assist;
}, 0);
var ratings = _.reduce(value, function (memo, num) {
return memo + num.Rating;
}, 0);
var position = {
Position: key,
Apps: apps,
Assists: assists,
Ratings: ratings,
Goals: goals
};
console.log(position); >> correct data
$scope.temp.push(position);
});
});
});
});
$q.all($scope.temp).then(function (data) {
console.log( data); >> show []
})
我做错了什么? 谢谢大家。
答案 0 :(得分:0)
$q.all
仅适用于承诺!即等待所有的所有承诺完成,然后运行'then'函数。您正在传递一个数组作为参数。要获得所需内容,请尝试以下操作:
$scope.temp = [];
angular.forEach(seasonStageIds, function (seasonStageId, index) {
var promise = playerService.getPlayerProfile(seasonStageId, $stateParams.params.playerSename).then(function (data) {
return playerService.getPlayerPositionPerSeason(seasonStageId, data.data.Id).then(function (data) {
return _.chain(data)
.groupBy('Position')
.map(function (value, key) {
var goals = _.reduce(value, function (memo, num) {
return memo + num.Goals;
}, 0);
var apps = _.reduce(value, function (memo, num) {
return memo + num.Apps;
}, 0);
var assists = _.reduce(value, function (memo, num) {
return memo + num.Assist;
}, 0);
var ratings = _.reduce(value, function (memo, num) {
return memo + num.Rating;
}, 0);
var position = {
Position: key,
Apps: apps,
Assists: assists,
Ratings: ratings,
Goals: goals
};
return position;
});
});
});
$scope.temp.push(promise);
});
$q.all($scope.temp).then(function (data) {
console.log( data);
});