ngResource and Json API spec

1.2k views Asked by At

I'm working with an API that follows the JSON API spec.

http://jsonapi.org/

I'm building an app in Ionic using ngResource, and the resource.query() method expects the response to be an array:

[
  {
    "id": 1,
    "foo": "bar"
  },
  {
  ...
  }
]

But the JSON API spec passes that nested under the data attribute:

{
  "data": [
    {
      "id": 1,
      "foo": "bar"
    },
    {
    ...
    }
  ]
}

How can I automatically post-process the response from the API to fulfill what ngResource is expecting?

2

There are 2 answers

0
aadarshsg On BEST ANSWER

Look into transformResponse and interceptor objects.

https://docs.angularjs.org/api/ngResource/service/$resource

EDIT: Adding code

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    return {
      'response': function(response) {
        response.data = response.data.data;
        return response;
      }
    };
  });

$httpProvider.interceptors.push('myHttpInterceptor');
0
Jahanzaib Aslam On

EDIT:

As you can see below, the query method is built to handle arrays by default.

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'}
};
  1. you can use simple GET method to get object list response from your api.
  2. OR you can change query default behavior to this way.

:

var config = { method:'GET', isArray: false };
var url = 'http://jsonapi.org';
$resource(url, {}, {query: config});

for more detail. Please check https://docs.angularjs.org/api/ngResource/service/$resource