Skip to content

Instantly share code, notes, and snippets.

@xergiodf
Created November 26, 2018 19:49
Show Gist options
  • Select an option

  • Save xergiodf/3d7b4f803748fb0abfbc9ece3afaedce to your computer and use it in GitHub Desktop.

Select an option

Save xergiodf/3d7b4f803748fb0abfbc9ece3afaedce to your computer and use it in GitHub Desktop.
AngularJS Interceptor
(function () {
'use strict';
angular.module('some.module')
.controller('LoginController', loginController);
/** @ngInject */
function loginController(localStorageService, AuthService) {
...
function login() {
AuthService.attemptLogin(vm.data).then(function (response) {
...
var auth = response;
localStorageService.set('bearer', auth.tokenAuth);
...
}, function (err) {
console.error(err)
});
}
}
})();
(function () {
'use strict';
angular.module('some.module', [
'someDependency'
])
.config(InterceptorConfig);
/*@ngInject*/
function InterceptorConfig($httpProvider) {
$httpProvider.interceptors.push(['$q', 'localStorageService', 'AuthService',
function ($q, localStorageService, AuthService) {
return {
'request': function (config) {
// Check if authenticated
if (!AuthService.isAuth()) {
// Do something if not authenticated
}
// Setup token
config.headers = config.headers || {};
var token = localStorageService.get('bearer') || null;
if (token)
config.headers.Authorization = 'Bearer ' + token;
return config;
},
'response': function(response) {
return response || $q.when(response);
},
'responseError': function (error) {
angular.element('#loader').hide();
if (error.status === 401 || error.status === 403) {
// Do something on error
}
return $q.reject(response);
}
};
}]);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment