Skip to content

Instantly share code, notes, and snippets.

@cedricziel
Created April 21, 2013 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cedricziel/5431433 to your computer and use it in GitHub Desktop.
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…
{
count: 1,
payload: [
propOne: 'TestVal'
arr: [
propTwo: 'TestVal2'
]
],
status: 200
}
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