Forked from georgepaoli/Angular HTTP Interceptor.js
Created
October 18, 2017 11:27
-
-
Save yusufola/4e5ea7d56778af0663ce63094da4e5d4 to your computer and use it in GitHub Desktop.
Angular HTTP Interceptor Sample
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
// Create HTTP interceptor (https://docs.angularjs.org/api/ng/service/$http - Interceptors topic) | |
App.factory('AuthInterceptor', ['$window', '$q', '$location', function ($window, $q, $location) { | |
return { | |
request: function (config) { | |
config.headers = config.headers || {}; | |
config.headers.ContentType = 'application/json; charset=UTF-8'; | |
if (myGlobalVar.getToken()) { | |
// populate header custom fields | |
config.headers.Authorization = 'Bearer ' + myGlobalVar.getToken().access_token; | |
config.headers.iduser = myGlobalVar.getToken().iduser; | |
config.headers.name = myGlobalVar.getToken().name; | |
config.headers.email = myGlobalVar.getToken().email; | |
config.headers.birthdate = myGlobalVar.getToken().birthdate; | |
config.headers.phone = myGlobalVar.getToken().phone; | |
config.headers.routeurl = $location.url(); | |
} | |
return config || $q.when(config); | |
}, | |
response: function (response) { | |
return response || $q.when(response); | |
}, | |
responseError: function (rejection) { | |
if (rejection.status === 401) { | |
$window.location.href = myGlobalVar.appBasePath + 'account/login'; | |
} | |
return $q.reject(rejection); | |
} | |
}; | |
}]); | |
// Register the previously created AuthInterceptor. | |
App.config(function ($httpProvider) { | |
$httpProvider.interceptors.push('AuthInterceptor'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment