我需要将必要的HMAC标头附加到请求中。这应该不是很困难,但我开始感到沮丧。以下代码有什么问题。我正在进行的实际http调用;我自己运行了这个调用,它返回了必要的数据。它在拦截器内部不起作用。
我只想在为此拦截器添加白名单或黑名单以及其他可自定义数据之前使当前实现正常工作。这不是关于hmac的问题,而是承诺。
此拦截器中的错误是整个承诺行从$ http(...)开始。当我删除此块并按原样使用它(减去承诺执行)它工作正常。一旦我取消注释该线就会卡在一个循环中并崩溃铬。我读过的每个地方都说它是如何完成的,但这显然不起作用。
function requestInterceptor(config){
var $http = $injector.get('$http');
var deferred = $q.defer();
$http.get(hmacApiEndpoint, {cache: true}).then(function(data){
console.log('HMAC - Success', data)
deferred.resolve(config)
}, function(config){
console.log('HMAC - Error', config)
deferred.resolve(config)
})
return deferred.promise;
}
return {
request: requestInterceptor
};
这是否与angulars $ http promise与'$ q'不同的实现有关?
答案 0 :(得分:5)
It doesn't look like you are actually amending the config
with the newly obtainted HMAC.
Also, you'd need to protect against your requestInterceptor
intercepting the call to obtain the HMAC, thus resulting in an infinite loop.
And lastly, you don't need deferred
here - just return the promise produced by $http
(or $http.then()
):
function requestInterceptor(config){
var $http = $injector.get('$http');
// just return, if this is a call to get HMAC
if (config.url === hmacApiEndpoint) return config;
return $http.get(hmacApiEndpoint, {cache: true})
.then(function(response){
console.log('HMAC - Success', response.data)
// not sure where the HMAC needs to go
config.headers.Authorization = response.data;
return config;
})
.catch(function(){
return $q.reject("failed to obtain HMAC");
});
}
return {
request: requestInterceptor
};