2

I am using query function of $resource as follows

resource.query(function(details){
    $scope.details=details;
    console.log($scope.details);

})
console.log($scope.details);

In above code first console.log is printing the exact data. but second one is showing undefined. Console Output is as Follows.

angular.js:10661 XHR finished loading: GET "http://localhost:9000/app/myLeaveApplication/myLeaveApplication.html". 

myLeaveApplicationController.js:10 undefined

angular.js:10661 XHR finished loading: GET "http://localhost:9000/assets/data/data.json"

myLeaveApplicationController.js:7 
[Resource, Resource, Resource, $promise: Promise, $resolved: true]

So anyone please help me knowing why this is happening?

Gaurav Bhusare
  • 195
  • 1
  • 17
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil May 18 '16 at 06:46

2 Answers2

1

This is because resource.query is an asynchronous method, so line 10 is executed before the callback function, and it's still undefined. Then, once the query is finished, it calls the callback and $scope.details now already has the data, so this is an expected behavior. This is a common confusion for programmers new to JS.

  • Common enough to have a canonical [StackOverflow question and answer](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) so you can vote to close as a duplicate instead of repeating the same answer – Phil May 18 '16 at 06:55
  • Thank you sir for your help. I edit my code and got the answer. I just need to call query method using a variable. – Gaurav Bhusare May 18 '16 at 07:03
-1

This is because resource.query is the asynchronus method so console.log($scope.details); line executed before details is assigned to $scope.details

You can try the below solution:

resource.query(function(details){
    $scope.details=details;
    console.log($scope.details);

});

$scope.$watch('details', function() {
   console.log($scope.details);
});
Suneet Bansal
  • 2,664
  • 1
  • 14
  • 18