Skip to content

Instantly share code, notes, and snippets.

@MrRaindrop
Last active December 24, 2015 02:09
Show Gist options
  • Save MrRaindrop/6728619 to your computer and use it in GitHub Desktop.
Save MrRaindrop/6728619 to your computer and use it in GitHub Desktop.
how to define a $http interceptor in angular.
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config || $q.when(config);
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response || $q.when(response);
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
};
}
});
$httpProvider.interceptors.push('myHttpInterceptor');
// register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
// same as above
},
'response': function(response) {
// same as above
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment