-
-
Save wpsmith/f5b2dca4da5aa6412ed94da5203a0bc4 to your computer and use it in GitHub Desktop.
Angular $httpProvider interceptor to handle requests and also cancels request on state change
This file contains 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
/** | |
* This array is needed for canceling requests when changing the state/route. | |
* @type {Array} | |
*/ | |
var currentRequests = []; | |
/** | |
* Handles route changes. | |
*/ | |
app.run(['$rootScope', function($rootScope) { | |
/** | |
* Cancels pending requests | |
*/ | |
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { | |
angular.forEach(currentRequests, function(request) { | |
request.resolve(); // cancel | |
}); | |
currentRequests = []; | |
}); | |
}]); | |
/** | |
* Authentication with token and email for every server request. (Sets HTTP headers) | |
* | |
* This interceptor shows the error from the server (i18n key). | |
* Also sets global error variable if the request fails and redirects the user to '/' when he is not authorized. | |
* @see http://engineering.talis.com/articles/client-side-error-logging/ | |
*/ | |
app.factory('authInterceptor', ['$rootScope', '$q', '$cookies', '$location', '$timeout', function ($rootScope, $q, $cookies, $location, $timeout) { | |
return { | |
request: function (config) { | |
delete $rootScope.errorKey; | |
config.headers = config.headers || {}; | |
config.headers['X-AUTH-TOKEN'] = $cookies['AUTH-TOKEN']; | |
config.headers['X-AUTH-EMAIL'] = $cookies['AUTH-EMAIL']; | |
if(!/\.html/.test(config.url)) { | |
var defer = $q.defer(); | |
currentRequests.push(defer); | |
config.timeout = defer.promise; | |
} | |
return config; | |
}, | |
responseError: function (response) { | |
var status = response.status; | |
// unauthorized -> redirect | |
if(status === 401) { | |
$rootScope.error = 'global.server_errors.unauthorized'; | |
$timeout(function () { | |
$location.path('/'); | |
}, 3000); | |
} else if(status !== 0) { | |
$rootScope.showErrorMsg = true; // general error message | |
$timeout(function() { | |
$rootScope.showErrorMsg = false; | |
}, 10000); | |
} | |
return $q.reject(response); | |
} | |
}; | |
}]); | |
app.config(['$httpProvider', function($httpProvider) { | |
$httpProvider.interceptors.push('authInterceptor'); | |
}]); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment