Skip to content

Instantly share code, notes, and snippets.

@prasannapattam
Created August 12, 2014 16:49
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 prasannapattam/b8c0827dd8b67826e4da to your computer and use it in GitHub Desktop.
Save prasannapattam/b8c0827dd8b67826e4da to your computer and use it in GitHub Desktop.
AngularJS interceptor code which preprocesses the http response sent from a RESTful Web API
'use strict';
angular.module('appinterceptors').factory('WebAPIInterceptor', WebAPIInterceptor);
WebAPIInterceptor.$inject = ['$q'];
function WebAPIInterceptor($q) {
return {
request: request,
requestError: requestError,
response: response,
responseError: responseError
};
//request success
function request(config) {
// Return the config or promise.
return config || $q.when(config);
}
//request error
function requestError(rejection) {
// Return the promise rejection.
return $q.reject(rejection);
}
// response success
function response(response) {
//checking whether we got our AjaxModel
if (response.data.hasOwnProperty("Success") && response.data.hasOwnProperty("Message") && response.data.hasOwnProperty("Model")) {
if (response.data.Success === false) {
//as needed show error message to the user
//reject the response
return $q.reject(response);
}
else {
response.data = response.data.Model;
}
}
// Return the response or promise.
return response || $q.when(response);
}
//response Error
function responseError(rejection) {
// Return the promise rejection.
return $q.reject(rejection);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment