Skip to content

Instantly share code, notes, and snippets.

@funkytaco
Forked from gnomeontherun/angularjs-interceptor.js
Last active August 29, 2015 14:13
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 funkytaco/d0dd9d63e7891138b3c7 to your computer and use it in GitHub Desktop.
Save funkytaco/d0dd9d63e7891138b3c7 to your computer and use it in GitHub Desktop.
Intercept XHR/Ajax requests with AngularJS http interceptors. This allows you to globally intercept and modify requests and responses. You don't need to declare all of the methods, just the ones you need. Some example uses would be logging errors, adding extra headers, or triggering 'loading' screens. This intercepts ALL requests/responses, so y…
// Intercepting HTTP calls with AngularJS.
angular.module('MyApp', [])
.config(function ($provide, $httpProvider) {
// Intercept http calls.
$provide.factory('MyHttpInterceptor', function ($q) {
return {
// On request success
request: function (config) {
// console.log(config); // Contains the data about the request before it is sent.
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
// On request failure
requestError: function (rejection) {
// console.log(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response success
response: function (response) {
// console.log(response); // Contains the data from the response.
// Return the response or promise.
return response || $q.when(response);
},
// On response failture
responseError: function (rejection) {
// console.log(rejection); // Contains the data about the error.
// Return the promise rejection.
return $q.reject(rejection);
}
};
});
// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('LoggingHttpInterceptor');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment