0

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

1 Answer 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.

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yup just to point out why it's wrong, .query() is asynchronous so it doesn't finish immediately so it needs a callback function to trigger once it's done with it's work. Also note its good to include error handling functions as well ($qProvider now complains by default if you don't have this)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.