I have an array that I get from a service but in the controller I get an empty value in the forEach()
function. This is the code.
我有一个从服务获得的数组但在控制器中我在forEach()函数中得到一个空值。这是代码。
Controller
调节器
Here, both 'products' and 'copyProducts' are empty. I need to work with the 'copyProducts' array into the forEach()
function.
这里,'products'和'copyProducts'都是空的。我需要将'copyProducts'数组用于forEach()函数。
app.controller("controllerApp", function($scope, serviceApp){
var products = serviceApp.query();
$scope.copyProducts = products;
angular.forEach($scope.copyProducts, function(value, key){
console.log("object: "+value);
})
});
Service
服务
app.factory("serviceApp", function($resource){
return $resource("products.json", {}, {
getAll: {
method: "GET",
isArray: true
}
})
})
1 个解决方案
#1
6
Your code is wrong since .query()
is asynchronous so it doesn't finish immediately and the result is not ready on the next line synchronously. So it needs a callback function to trigger once it's done with it's work.
您的代码是错误的,因为.query()是异步的,因此它不会立即完成,并且结果在下一行同步时没有准备好。所以它需要一个回调函数,一旦完成它的工作就会触发。
serviceApp.query().$promise.then(function(res) {
$scope.products = res;
$scope.copyProducts = res;
angular.forEach($scope.copyProducts, function(item) {
console.log(item)
})
});
Alternative:
替代方案:
serviceApp.query({}, function(res, headers){
//etc
});
By the way, if you want to use the getAll
method you have defined in your resource then you would not be using query()
顺便说一句,如果你想使用你在资源中定义的getAll方法,那么你就不会使用query()
serviceApp.getAll().$promise.then(function(res){}).....etc
#1
6
Your code is wrong since .query()
is asynchronous so it doesn't finish immediately and the result is not ready on the next line synchronously. So it needs a callback function to trigger once it's done with it's work.
您的代码是错误的,因为.query()是异步的,因此它不会立即完成,并且结果在下一行同步时没有准备好。所以它需要一个回调函数,一旦完成它的工作就会触发。
serviceApp.query().$promise.then(function(res) {
$scope.products = res;
$scope.copyProducts = res;
angular.forEach($scope.copyProducts, function(item) {
console.log(item)
})
});
Alternative:
替代方案:
serviceApp.query({}, function(res, headers){
//etc
});
By the way, if you want to use the getAll
method you have defined in your resource then you would not be using query()
顺便说一句,如果你想使用你在资源中定义的getAll方法,那么你就不会使用query()
serviceApp.getAll().$promise.then(function(res){}).....etc