您好我正在尝试通过我的服务获取访问令牌,但问题是,当我没有访问令牌时,我尝试使用会创建令牌的特殊网址刷新页面,不幸的是该函数仍在运行,无需等待此URL加载新令牌。有没有办法增加承诺,或者你有不同的方法吗?如果您有任何想法,请告诉我。谢谢!!
代码:
app.factory('HttpInterceptor', function ($q, $window, CustomService) {
return {
request: function (config) {
if(CustomService.getAccessToken() == undefined) {
$window.location.href = CustomService.getURL();
}
config.headers.Authorization = 'Bearer ' + CustomService.getAccessToken(); // this is still undefined since window.location.href is still loading
return $q.when(config);
},
responseError: function(response) {
if(response.status == 401){
$window.location.href = CustomService.getURL();
}
return $q.reject(response)
}
};
});
app.service('CustomService', function($location) {
this.getAccessToken = function() {
if(getParam('token')){
this.token = getParam('token');
}
return this.token;
}
this.getURL = function(){
var redirectUrl = //adds url
return redirectUrl;
}
function getParam(name) {
var token = null;
token = //adds token info
return token;
}
});
答案 0 :(得分:1)
您可以在config.url
函数中使用request
。
CustomService.getURL()
返回的网址格式。config.url
是否与CustomService.getURL()
匹配且访问令牌为空或已过期。如果检查true
然后继续$window.location.href = CustomService.getURL();
如果检查结果为false
,则会重定向到特殊网址$window.location.href = CustomService.getURL();
示例请求代码:
request: function (config) {
if(CustomService.getAccessToken() == undefined && config.url.indexOf('oauth2')) {
//'oauth2' can be of any pattern
$window.location.href = CustomService.getURL();
}
else{
config.headers.Authorization = 'Bearer ' + CustomService.getAccessToken();
// this is still undefined since window.location.href is still loading
}
return $q.when(config);
},