这是我正在处理的代码。
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) {