gpt4 book ai didi

javascript - AngularJS:将服务注入(inject) HTTP 拦截器(循环依赖)

转载 作者:IT王子 更新时间:2023-10-29 02:39:47 24 4
gpt4 key购买 nike

我正在尝试为我的 AngularJS 应用程序编写一个 HTTP 拦截器来处理身份验证。

此代码有效,但我担心手动注入(inject)服务,因为我认为 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;
}
};
})
}]);

我开始做的,但遇到了循环依赖问题:

    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');
});

我担心的另一个原因是 section on $http在 Angular Docs 中似乎展示了一种将依赖项以“常规方式”注入(inject) Http 拦截器的方法。在“拦截器”下查看他们的代码片段:

// 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');

上面的代码应该放哪里呢?

我想我的问题是执行此操作的正确方法是什么?

谢谢,我希望我的问题足够清楚。

最佳答案

这就是我最终做的

  .config(['$httpProvider', function ($httpProvider) {
//enable cors
$httpProvider.defaults.useXDomain = true;

$httpProvider.interceptors.push(['$location', '$injector', '$q', function ($location, $injector, $q) {
return {
'request': function (config) {

//injected manually to get around circular dependency problem.
var AuthService = $injector.get('Auth');

if (!AuthService.isAuthenticated()) {
$location.path('/login');
} else {
//add session_id as a bearer token in header of all outgoing HTTP requests.
var currentUser = AuthService.getCurrentUser();
if (currentUser !== null) {
var sessionId = AuthService.getCurrentUser().sessionId;
if (sessionId) {
config.headers.Authorization = 'Bearer ' + sessionId;
}
}
}

//add headers
return config;
},
'responseError': function (rejection) {
if (rejection.status === 401) {

//injected manually to get around circular dependency problem.
var AuthService = $injector.get('Auth');

//if server returns 401 despite user being authenticated on app side, it means session timed out on server
if (AuthService.isAuthenticated()) {
AuthService.appLogOut();
}
$location.path('/login');
return $q.reject(rejection);
}
}
};
}]);
}]);

注意:$injector.get 调用应该在拦截器的方法内,如果您尝试在其他地方使用它们,您将继续在 JS 中出现循环依赖错误。

关于javascript - AngularJS:将服务注入(inject) HTTP 拦截器(循环依赖),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20647483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com