Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  168] [ 5]  / answers: 1 / hits: 16692  / 12 Years ago, wed, august 8, 2012, 12:00:00

I'm using an API that returns JSON data in this format:



{
paging: {
previous: null,
next: null
},
data: [
{ title: 'First Item' },
{ title: 'Second Item' },
...
]
}


I'm using Angular's $resource service to fetch this data.

My code - which is located in a controller - goes something like this:



var Entity = $resource('/api/entities');
var entities = $scope.entities = Entity.get();


And then, in the view, I can display the data like this:



<ul>
<li ng-repeat=entity in entities.data>{{entity.title}}</<li>
</ul>


It all works fine, but:




  • I'd rather expose only the contents of entities.data to the view, instead of the whole entities object. How can I intercept the data returned by the GET request to modify it before it populates $scope.entities?

  • Correlated question: since I am fetching an array of data, it would be cleaner to use Entity.query() instead of Entity.get(). But if I use Entity.query() in the code above, I get an error TypeError: Object # has no method 'push'. This makes sense, since the API is returning an object instead of an array (hence, no 'push' method on the object). Again, if I could extract the .data attribute from the response, I'd have an array.



Following these indications by Dan Boyon, I managed to customize the default $resource service and to override the .get() or .query() methods, but I'm not sure where to go from there.


More From » angularjs

 Answers
5

I don't think you need to modify the get or query defaults. Just use the success callback to do what you want. It should be more robust as well.



Entity.get(
{}, //params
function (data) { //success
$scope.entities = data.data;
},
function (data) { //failure
//error handling goes here
});


Html will be cleaner, too:



 <ul>
<li ng-repeat=entity in entities>{{entity.title}}</<li>
</ul>


By the way, I usually declare services for my resources and then inject them into my controllers as I need them.



 myServices.factory('Entity', ['$resource', function ($resource) {
return $resource('/api/entities', {}, {
});
}]);

[#83775] Tuesday, August 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carlymykalac

Total Points: 740
Total Questions: 91
Total Answers: 91

Location: Sudan
Member since Thu, May 7, 2020
4 Years ago
;