Reputation: 23
Alrighty, for an internship project I am trying to create a simple client for a REST API. The current client is using regular angularJS, but I need to use Restangular for this.
I have been searching around a lot, trying out a lot of things, but nothing quite helped me do what I want, or understand what needs to happen.
This is the code snippet that needs to turn into Restangular
$http.get('/rest/programarticle/', {
'format': 'json'
}).success(function(data, status, headers, config) {
$scope.articles = angular.articles = data.results;
});
This picks up JSON data which contains some meta data, aswell as an array (results):
{
"count": 3,
"next": null,
"previous": null,
"results": [
{
"id": 100,
"catalog": 7,
"catalog_alias": "placeHolder",
"program": 7,
"name": "placeHolder"
},
{
"id": 92,
"catalog": 6,
"catalog_alias": "placeHolder",
"program": 6,
"name": "placeHolder"
},
{
"id": 84,
"catalog": 5,
"catalog_alias": "string",
"program": 5,
"name": "placeHolder"
}
]
}
I have my baseUrl configured correctly, and I tried this out:
var testArticles = Restangular.all('programarticle').getList();
console.log(testArticles);
Using the following ResponseInterceptor:
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
if (operation === "getList") {
extractedData = data.results;
extractedData.count = data.count;
extractedData.next = data.next;
extractedData.previous = data.previous;
} else {
extractedData = data.data;
}
return extractedData;
});
But this still results in something I can't work with in the console:
Promise {$$state: Object, restangularCollection: true, $object: Array[0]}
Which when opened shows the following:
$$state: Object
$object: Array[7]
call: wrapper()
get: wrapper()
push: wrapper()
restangularCollection: true
__proto__: Promise
It does show an array($object), but I cannot reach it using
console.log(testArticles.$object);
Should I be using .get() instead of getList()? If so, how do I use this correctly?
Thank you for your time and please suggest, I am still a beginner.
Upvotes: 2
Views: 222
Reputation: 7752
What the get
/getList
functions from restangular return are actually Promises, not the JSON objects retrieved themselves. Promises are a way of abstracting an asynchronous call with a more manageable interface. They stand for an expected future result.
What you need to know is that to get the actual result of the Promise, you must add a callback using the then
function, like so:
Restangular.all('programarticle').getList().then(function (articles) {
$scope.articles = articles;
});
Read more about promises here.
Upvotes: 1