Sto cercando di scrivere un intercettore HTTP per la mia app AngularJS per gestire l'autenticazione.
Questo codice funziona, ma sono preoccupato per l'inserimento manuale di un servizio poiché pensavo che Angular dovesse gestirlo automaticamente:
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;
}
};
})
}]);
Quello che ho iniziato a fare, ma mi sono imbattuto in problemi di dipendenza circolare:
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');
});
Un altro motivo per cui sono preoccupato è che la sezione su $ http in Angular Docs sembra mostrare un modo per ottenere le dipendenze iniettate in "modo regolare" in un intercettore Http. Vedi lo snippet di codice in "Interceptor":
// 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');
Dove dovrebbe andare il codice sopra?
Immagino che la mia domanda sia qual è il modo giusto per farlo?
Grazie, e spero che la mia domanda sia stata abbastanza chiara.
$http
. L'unico modo per aggirare il problema è quello di usarlo $injector.get
, ma sarebbe bello sapere se esiste un buon modo per strutturare il codice per evitarlo.