Reputation: 3995
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?
Upvotes: 2
Views: 1259
Reputation: 2834
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'}
};
:
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
Upvotes: 1
Reputation: 2089
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');
Upvotes: 5