Created
June 3, 2016 13:55
-
-
Save Kashkovsky/e9ac38bd3b5f3083f29f1124c9d90bd6 to your computer and use it in GitHub Desktop.
AngularJS common interceptor
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
(function () { | |
'use strict'; | |
app.factory('authInterceptorService', authInterceptorService); | |
authInterceptorService.$inject = ['$q', 'localStorageService', 'constantsService']; | |
function authInterceptorService ($q, localStorageService, constantsService) { | |
var authInterceptorServiceFactory = {}; | |
function request (config) { | |
loading(true); | |
config.headers = config.headers || {}; | |
var authData = localStorageService.get('authorizationData'); | |
if (authData) { | |
config.headers.Authorization = 'Bearer ' + authData.token; | |
} | |
return config; | |
} | |
function response(response) { | |
loading(false); | |
if (response.data && response.data.url) { | |
response.data.url = processDataUrl(response.data.url); | |
} | |
return response; | |
} | |
function responseError(response) { | |
loading(false); | |
var status = response.status; | |
if (status === 400) { | |
console.log('Bad request'); | |
} | |
return response; | |
} | |
//show some spinner when loading... | |
function loading(state) { | |
if (state) { | |
angular.element(document.querySelector('#loading')).addClass('csspinner'); | |
angular.element(document.getElementsByClassName('form-ctrl')).attr('disabled', 'true'); | |
} else { | |
angular.element(document.querySelector('#loading')).removeClass('csspinner'); | |
angular.element(document.getElementsByClassName('form-ctrl')).removeAttr('disabled'); | |
} | |
} | |
function processDataUrl(url) { | |
switch (url.type) { | |
case 1: | |
url.name = constantsService.ProfileImagePath + url.name; | |
break; | |
default: | |
break; | |
} | |
return url; | |
} | |
authInterceptorServiceFactory.request = request; | |
authInterceptorServiceFactory.response = response; | |
authInterceptorServiceFactory.responseError = responseError; | |
return authInterceptorServiceFactory; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment