Created
August 28, 2017 20:53
-
-
Save georgepaoli/48a9db51e6b1f7e78bb10651a92a6099 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