这是我工作的代码。
appControllers.controller('MyaSellerOrderCtrl', ['$scope', '$rootScope', 'Order', '$http',
function($scope, $rootScope, Order, $http) {
$scope.results = [];
$scope.getData = function() {
$http.get('api/orders/business/?user_id=' + $rootScope.user.user_id).success(function(data){
for (var i = 0; i < data.length; i++) {
$http.get('api/orders/seller/?business_id=' + data[i].business_id).success(function(data1){
// console.log(data1);
$scope.results[i] = data1;
});
}
console.log($scope.results);
});
};
$scope.getData();
}]);
问题是,$ scope.results是空的,而功能正常工作。有人说这是由于$ http的异步性质。你能修改代码来使用promise来避免错误吗?
现在我更新的代码所示
appControllers.controller('MyaSellerOrderCtrl', ['$scope', '$rootScope', '$http','$q',
function($scope, $rootScope, $http, $q) {
$scope.results = [];
function _getOrdersById(id) {
return $http.get('api/orders/business/?user_id=' + id);
}
function _parseOrders(orders) {
var _promises = [];
orders.forEach(function (order, index) {
var _promise = $http.get('api/orders/seller/?business_id=' + order.business_id).then(function (response) {
$scope.results[index] = response;
});
_promises.push(_promise);
});
return $q.all(_promises);
}
$scope.getData = function() {
_getOrdersById($rootScope.user.user_id)
.then(_parseOrders)
.then(function() {
console.log($scope.results);
}, function (error) {
console.error(error);
});
};
$scope.getData();
}
]);
,但它仍然显示错误
159线点到线
orders.forEach(function(order,index) {
$ http已经是一个承诺。 – 2014-10-07 16:36:57