I'm currently working on developing an HTTP interceptor for my AngularJS application to manage authentication.
Although the code I have is functional, I am wary of manually injecting a service as I believed Angular is designed to handle this process automatically:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push(function ($location, $injector) {
return {
'request': function (config) {
//manually injected to resolve circular dependency issue.
var AuthService = $injector.get('AuthService');
console.log(AuthService);
console.log('in request interceptor');
if (!AuthService.isAuthenticated() && $location.path != '/login') {
console.log('user is not logged in.');
$location.path('/login');
}
return config;
}
};
})
}]);
Initially, I attempted a different approach but encountered circular dependency challenges:
app.config(function ($provide, $httpProvider) {
$provide.factory('HttpInterceptor', function ($q, $location, AuthService) {
return {
'request': function (config) {
console.log('in request interceptor.');
if (!AuthService.isAuthenticated() && $location.path != '/login') {
console.log('user is not logged in.');
$location.path('/login');
}
return config;
}
};
});
$httpProvider.interceptors.push('HttpInterceptor');
});
Furthermore, observing the documentation section about $http in the Angular Docs revealed a method for injecting dependencies in a more conventional manner within an Http interceptor. Refer to the sample code listed under "Interceptors":
// registering the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// perform actions upon success
return config || $q.when(config);
},
// optional method
'requestError': function(rejection) {
// execute actions upon error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// perform actions upon success
return response || $q.when(response);
},
// optional method
'responseError': function(rejection) {
// execute actions upon error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
};
}
});
$httpProvider.interceptors.push('myHttpInterceptor');
Specifically where should the above code implementation be placed?
Essentially, my query revolves around determining the correct procedure for accomplishing this task.
Thank you, and I trust that my inquiry was articulated clearly enough.