2

i'm trying to access a specific position of my array of resources, that came from a query but in my console.log it doesn't appear.

$scope.a = [];
var resourceGet = $resource('myurl');
$scope.a = resourceGet.query(function(data){
      return data;
}, function(error){
      console.log(error);
});
console.log($scope.a[1]);

Nothing on the console. But, i can show $scope.a using ng-repeat.

What am i doing wrong?

1
  • 1
    The data is not immediately available. During console.log($scope.a[1]), the query may not have returned the data, hence nothing is displayed in console. Commented Dec 19, 2015 at 17:07

1 Answer 1

3

That's because you're dealing with asynchronous data. Your console.log executes before the callbacks you give to query, at a moment when the data hasn't been loaded yet. The code you wrote (except the callback) is synchronous.

Edit : here's an example of simple data loading with $http. I suggest using $http for simple tasks as $resource is more about CRUD operations. Personnally I've never used $resource.

http://codepen.io/anon/pen/zrqbxj?editors=101

Sign up to request clarification or add additional context in comments.

2 Comments

Whats the best way to change/edit/access the incomming data from get requests right after the request?? Use $http?
You can change/edit/access in the block where you have 'return data' statement. Because, it is the place where the incoming data is actually available. resourceGet.query(function(data){ $scope.a = data} , function(error){}); shoud work.

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.