简体   繁体   中英

AngularJS - forEach() with empty array from $resource

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 .

Controller

Here, both 'products' and 'copyProducts' are empty. I need to work with the 'copyProducts' array into the forEach() function.

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
        }
    })
})

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.

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()

  serviceApp.getAll().$promise.then(function(res){}).....etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM