Search code examples
javascriptangularjsngresource

Understanding AngularJS's $resource


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?


Solution

  • $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.