Created
January 19, 2016 17:51
-
-
Save tkssharma/746cd2a67f4ec5925e15 to your computer and use it in GitHub Desktop.
Creating HTTP angular Interceptor to intercept error from server side
This file contains hidden or 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
/** | |
* Angular factory on HTTP interceptor | |
*/ | |
(function() { | |
angular.module('Codefun') | |
.config(function ($httpProvider, $provide) { | |
$provide.factory('httpInterceptor', function ($q, $rootScope, AUTH_EVENTS) { | |
return { | |
'request': function (config) { | |
// intercept and change config: e.g. change the URL | |
// for every request sending some ID token in HTTP header | |
if ($window.localStorage['alakarte-food.token']) { | |
config.headers['x-access-token'] = $window.localStorage['token']; | |
config.headers['x-user-id'] = $window.localStorage['user_id']; | |
//config.headers.Authorization = 'Token token=" ' + | |
// $window.localStorage['alakarte-food.token'] +'"'; | |
} | |
return config || $q.when(config); | |
}, | |
'response': function (response) { | |
// we can intercept and change response here... | |
// broadcasting 'httpResponse' event | |
//$rootScope.$broadcast('httpResponse', response); | |
return response || $q.when(response); | |
}, | |
'requestError': function (rejection) { | |
// broadcasting 'httpRequestError' event | |
//$rootScope.$broadcast('httpRequestError', rejection); | |
return $q.reject(rejection); | |
}, | |
'responseError': function (rejection) { | |
$rootScope.$broadcast({ | |
401: AUTH_EVENTS.notAuthenticated, | |
}[rejection.status], rejection); | |
return $q.reject(rejection); | |
} | |
}; | |
}); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment