Search code examples
angularjsangular-resource

Cant Access data out of $resource.query() in Angular JS


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?


Solution

  • 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.