Angular - 带有请求拦截器的异步操作
Angular - Asynchronous operation with request interceptor
我的请求拦截器如下所示:
var requestFactory = angular.module('queryParamsModule', [])
.factory('headerInterceptor', function($injector) {
return {
request: requestInterceptor
};
function requestInterceptor(req) {
var accessToken;
$injector.get('tokenService').accessToken().then(function(res) {
accessToken = res.access_token;
console.log(accessToken); >>>>> accessToken is populated fine!
req.headers = _.extend({
'Authorization': 'Bearer ' + accessToken
}, req.headers);
}, function(e) {
// error
});
return req;
}
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('headerInterceptor');
});
return queryParamsFactory;
这里的问题是,angular 不等待在请求中添加授权 Header 并在添加授权 header 之前推送拦截器。
有没有办法让我的 header 拦截器成为在 accessToken 承诺完成后解析的承诺的一部分?
正如the manual所说,
request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
所以应该是:
function requestInterceptor(req) {
return $injector.get('tokenService').accessToken().then(function(res) {
...
return req;
}, function(e) { ... });
}
我的请求拦截器如下所示:
var requestFactory = angular.module('queryParamsModule', [])
.factory('headerInterceptor', function($injector) {
return {
request: requestInterceptor
};
function requestInterceptor(req) {
var accessToken;
$injector.get('tokenService').accessToken().then(function(res) {
accessToken = res.access_token;
console.log(accessToken); >>>>> accessToken is populated fine!
req.headers = _.extend({
'Authorization': 'Bearer ' + accessToken
}, req.headers);
}, function(e) {
// error
});
return req;
}
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('headerInterceptor');
});
return queryParamsFactory;
这里的问题是,angular 不等待在请求中添加授权 Header 并在添加授权 header 之前推送拦截器。
有没有办法让我的 header 拦截器成为在 accessToken 承诺完成后解析的承诺的一部分?
正如the manual所说,
request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
所以应该是:
function requestInterceptor(req) {
return $injector.get('tokenService').accessToken().then(function(res) {
...
return req;
}, function(e) { ... });
}