3

I don't quite get how to properly use AngularJS's $resource. For example, I have a REST API that is returning data like this:

{
    "status": "success",
    "data": {
        "expand": "schema,names",
        "startAt": 0,
        "maxResults": 10,
        "total": 38,
        "issues": [{ ... }, { ... }, {...}, ...]
    }
}

Now what I am trying to figure out is how in AngularJS to use the $resource where each object in data.issues is returned as a resource (so in this case, get an array/collection of 10 resources) however it does not really seems like I can do that with AngularJS's $resource from the limited resource I have found on it, or can I?

pomber
  • 19,363
  • 9
  • 71
  • 90
ryanzec
  • 25,398
  • 36
  • 107
  • 160

3 Answers3

6

$resource is expecting a classic "RESTful" API source. This means you'd have an endpoint where GET, PUT, POST, DELETE methods would all effect a given resource type, and the body of those messages would only include the resource, not the resource and a bunch of metadata.

For what you're trying to do, if that's the API you're stuck with, you're probably going to have to use $http to roll your own, as it looks like the JSON it's responding with contains a bunch of metadata that $resource won't care about.

The only other option would be to write some sort of httpInterceptor that would translate what you're getting back from your web service as into something $resource can handle a little more seamlessly.

While, semantically, your web service is probably generically "RESTful", it's not RESTful in the current classic standard of what that means.

More information on REST here


EDIT: Outside of the above information, without seeing the signature of your web API or knowing what you're trying to do, it will be hard to answer your question in any more detail.

Community
  • 1
  • 1
Ben Lesh
  • 105,049
  • 47
  • 242
  • 231
3

With newer versions of angular, you can provide a callback to a resource action that will bypass an outer wrapper.

$resource('', {}, {
    query: {
        method: 'GET',
        isArray: true,
        transformResponse: function(response) {
            return JSON.parse(response).data.issues;
        }
    }
});

Then in your resource callback function

Issue.query({
    //query params
}, function(issues) {
    //issues will be an array of your issues that you can process
    //or just add to the scope to be iterated over              
});
Booker
  • 686
  • 1
  • 5
  • 16
1

Looking at the code, blesh is correct so what I did was modify the base $resource code in order to support custom encoders/decoders to make is any to have $resource be able to work with any REST API that might have a customized format. Made a pull request to angularjs hopping they will include it so I don't have to maintian this separate fork : https://github.com/angular/angular.js/pull/1514

ryanzec
  • 25,398
  • 36
  • 107
  • 160