Próbuję napisać przechwytywacz HTTP dla mojej aplikacji AngularJS do obsługi uwierzytelniania.
Ten kod działa, ale obawiam się ręcznego wstrzykiwania usługi, ponieważ pomyślałem, że Angular powinien obsługiwać to automatycznie:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push(function ($location, $injector) {
return {
'request': function (config) {
//injected manually to get around circular dependency problem.
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;
}
};
})
}]);
Co zacząłem robić, ale napotkałem problemy z zależnością cykliczną:
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');
});
Innym powodem, dla którego jestem zaniepokojony, jest to, że sekcja dotycząca $ http w Angular Docs wydaje się pokazywać sposób na wprowadzenie zależności w „zwykły sposób” do przechwytywacza HTTP. Zobacz ich fragment kodu w sekcji „Interceptory”:
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config || $q.when(config);
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response || $q.when(response);
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
};
}
});
$httpProvider.interceptors.push('myHttpInterceptor');
Gdzie powinien iść powyższy kod?
Myślę, że moje pytanie brzmi: jaki jest właściwy sposób, aby to zrobić?
Dziękuję i mam nadzieję, że moje pytanie było wystarczająco jasne.
$http
. Jedynym sposobem obejścia tego problemu jest użycie $injector.get
, ale byłoby wspaniale wiedzieć, czy istnieje dobry sposób na uporządkowanie kodu, aby tego uniknąć.