Skip to content

Instantly share code, notes, and snippets.

@g-alonso
Last active January 1, 2016 12:29
Show Gist options
  • Save g-alonso/8145162 to your computer and use it in GitHub Desktop.
Save g-alonso/8145162 to your computer and use it in GitHub Desktop.
Angular Http Interceptor
var interceptor = angular.module('Interceptor',[]);
interceptor.factory('HttpInterceptor', function ($q, $rootScope, $log) {
var numLoadings = 0;
return {
request: function (config) {
numLoadings++;
$rootScope.$broadcast("event:pendingRequests");
return config || $q.when(config)
},
response: function (response) {
if ((--numLoadings) === 0) {
$rootScope.$broadcast("event:allRequestsComplete");
}
return response || $q.when(response);
},
responseError: function (response) {
if (!(--numLoadings)) {
$rootScope.$broadcast("event:allRequestsComplete");
}
var status = response.status;
if (status === 401) {
$rootScope.$broadcast('event:loginRequired');
$log.info('broadcasted: event:loginRequired')
}
if (status === 403) {
$rootScope.$broadcast('event:accessDenied');
$log.info('broadcasted: event:accessDenied')
}
if (status === 500) {
$rootScope.$broadcast('event:internalServerError', response);
$log.info('broadcasted: event:internalServerError')
}
return $q.reject(response);
}
};
}).config(function ($httpProvider) {
$httpProvider.interceptors.push('HttpInterceptor');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment