Created
April 21, 2013 23:01
-
-
Save cedricziel/5431433 to your computer and use it in GitHub Desktop.
Untangeling a wrapped JSON response from a RESTful Service in AngularJS. This makes it pretty easy by registering a $http response Interceptor. In this case, the format of the returned JSON was like given in exampleResponse.json. Please note: This does in fact intercept ALL requests, made through $http (which are basically all http requests in a…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
count: 1, | |
payload: [ | |
propOne: 'TestVal' | |
arr: [ | |
propTwo: 'TestVal2' | |
] | |
], | |
status: 200 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('yourApp.services', ['ngResource']) | |
.config ($httpProvider) -> | |
$httpProvider.responseInterceptors.push('arrayHttpInterceptor') | |
.factory 'arrayHttpInterceptor', ($q) -> | |
(promise) -> | |
success = (response) -> | |
if(response.headers()['content-type'] == "application/json") | |
# is single item? | |
if (!response.data.total?) | |
response.data = response.data.payload[0] | |
if (response.data.payload?) | |
response.data = response.data.payload | |
response | |
error = (response) -> | |
$q.reject(response) | |
promise.then success, error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment