Last active
January 1, 2016 12:29
-
-
Save g-alonso/8145162 to your computer and use it in GitHub Desktop.
Angular Http Interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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