我正在尝试为我的AngularJS应用程序编写HTTP拦截器来处理身份验证.
这段代码有效,但我担心手动注入服务,因为我认为Angular应该自动处理:
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;
}
};
})
}]);
Run Code Online (Sandbox Code Playgroud)
我开始做的事情,但遇到循环依赖问题:
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 …Run Code Online (Sandbox Code Playgroud)