Skip to content

Instantly share code, notes, and snippets.

@georgepaoli
Created August 28, 2017 20:53
Show Gist options
  • Save georgepaoli/48a9db51e6b1f7e78bb10651a92a6099 to your computer and use it in GitHub Desktop.
Save georgepaoli/48a9db51e6b1f7e78bb10651a92a6099 to your computer and use it in GitHub Desktop.
Angular HTTP Interceptor Sample
// 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