Omar Lahlou
Omar Lahlou

Reputation: 1000

Get Restangular object attribute

After receivingRestangular object, myObject, that looks like:

enter image description here

To get the $object: array[2] field, I do myObject[0] and the result is undefined.

Here is my code:

r = Restangular.service("patient_messages")
myObject = r.getList() # This returns the object on picture above
console.log("$object", myObject[0]) # result: $object undefined 

Can anyone help me get that field?

Upvotes: 1

Views: 465

Answers (1)

Salem Ouerdani
Salem Ouerdani

Reputation: 7886

If you try this :

console.log("myObject", angular.toJson(myObject));

You'll get this output :

# myObject {"restangularCollection":true,"$object":[]}

Which is the real value of myObject, an almost empty object that will be filled in with data at some moment in the future: when the call completes to be precise. That explain the different results.

The Restangular instance you created in your controller will return a $q.defer().promise object which purpose is to allow for interested parties to get access to the result of the deferred task when it completes.

So myObject.$object[0] doesn't exist yet, your controller wont get to it until you invoque the promise.then() method which will return a new derived promise, that will look like the one you've been watching in your console :


replace in your code console.log("$object", myObject[0]) by this and it will work :

myObject.then(function(){
  console.log("$object", myObject.$object[0]);
});

Upvotes: 2

Related Questions