Angular http拦截器不适用于从拦截器内初始化的请求?
在我们的代码库中,对我们 api 的每个请求都有一个以 url 开头的 url,/api/
并且我们有一个拦截器,它使用我们 api 的实际地址更新这些请求(使得在开发和生产环境之间轻松切换一件事)。更新 url 后,如果存在访问令牌,拦截器还会添加 Authorization 标头。这一切都完美无缺。
但是,有时访问令牌已过期,但我们仍然有一个刷新令牌,在继续实际请求之前,我首先想向我们的 api 发出请求以获取新的访问令牌。
因此,在request
我们的拦截器部分,我们调用了一个负责刷新访问令牌的服务,并且在该then
方法返回的回调中,我们更新了原始请求的配置:
//This interceptor only applies to our api calls, do nothing for other requests
if(config.url.substring(0, API_PREFIX.length) !== API_PREFIX) {
return config;
}
config.url = config.url.replace(API_PREFIX, API_ENDPOINT);
// if we are authenticated, we add the authorization header already
if(AuthSessionService.isAuthenticated()) {
config.headers['Authorization'] = "Bearer " + AuthSessionService.getAccessToken();
return config;
}
// so we are not authenticated, but we still do have a refresh-token, this means, we should get a new access-token
if(AuthSessionService.hasRefreshToken()) {
var deferred = $q.defer(),
loginService = angular.injector(['MyApp']).get('LoginService');
loginService.refresh().then(function(result) {
config.headers['Authorization'] = "Bearer " + AuthSessionService.getAccessToken();
deferred.resolve(config);
}).catch(function() {
deferred.reject('Failed to refresh access token');
});
return deferred.promise;
}
//no access-token, no refresh-token, make the call without authorization headers
return config;
但是,登录服务发出的请求似乎没有应用拦截器,因此请求转到/api/login
而不是实际的 api 端点。
这是Angular的设计,当从拦截器的请求方法中发出新的http请求时不应用拦截器?