Created
November 26, 2018 19:49
-
-
Save xergiodf/3d7b4f803748fb0abfbc9ece3afaedce to your computer and use it in GitHub Desktop.
AngularJS Interceptor
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
| (function () { | |
| 'use strict'; | |
| angular.module('some.module') | |
| .controller('LoginController', loginController); | |
| /** @ngInject */ | |
| function loginController(localStorageService, AuthService) { | |
| ... | |
| function login() { | |
| AuthService.attemptLogin(vm.data).then(function (response) { | |
| ... | |
| var auth = response; | |
| localStorageService.set('bearer', auth.tokenAuth); | |
| ... | |
| }, function (err) { | |
| console.error(err) | |
| }); | |
| } | |
| } | |
| })(); |
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
| (function () { | |
| 'use strict'; | |
| angular.module('some.module', [ | |
| 'someDependency' | |
| ]) | |
| .config(InterceptorConfig); | |
| /*@ngInject*/ | |
| function InterceptorConfig($httpProvider) { | |
| $httpProvider.interceptors.push(['$q', 'localStorageService', 'AuthService', | |
| function ($q, localStorageService, AuthService) { | |
| return { | |
| 'request': function (config) { | |
| // Check if authenticated | |
| if (!AuthService.isAuth()) { | |
| // Do something if not authenticated | |
| } | |
| // Setup token | |
| config.headers = config.headers || {}; | |
| var token = localStorageService.get('bearer') || null; | |
| if (token) | |
| config.headers.Authorization = 'Bearer ' + token; | |
| return config; | |
| }, | |
| 'response': function(response) { | |
| return response || $q.when(response); | |
| }, | |
| 'responseError': function (error) { | |
| angular.element('#loader').hide(); | |
| if (error.status === 401 || error.status === 403) { | |
| // Do something on error | |
| } | |
| return $q.reject(response); | |
| } | |
| }; | |
| }]); | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment