Angularjs 带';通知';承诺
我有angular responseError拦截器,它实现了在前一次尝试失败时向服务器重新发送请求的逻辑。此外,拦截器还返回“通知”承诺,就当前状态保持联系Angularjs 带';通知';承诺,angularjs,unit-testing,mocha.js,sinon,chai,Angularjs,Unit Testing,Mocha.js,Sinon,Chai,我有angular responseError拦截器,它实现了在前一次尝试失败时向服务器重新发送请求的逻辑。此外,拦截器还返回“通知”承诺,就当前状态保持联系 return { responseError: function(response) { var retries = angular.isDefined(response.config.headers['X-RETRIES']) ? response.config.headers['X-RETRI
return {
responseError: function(response) {
var retries = angular.isDefined(response.config.headers['X-RETRIES']) ? response.config.headers['X-RETRIES'] : 0;
response.config.headers['X-RETRIES'] = retries + 1;
if (response.config.headers['X-RETRIES'] <= MAX_XHR_ATTEMPTS) {
var $http = $injector.get('$http'),
defer = $q.defer();
$timeout(function() {
defer.notify('trying');
defer.resolve($http(response.config));
}, 1000);
return defer.promise;
} else {
return $q.reject(response);
}
}
};
}
但承诺并没有返回任何状态。若我试图更改拦截器以在发生错误时返回“拒绝”承诺(并没有超时和额外的拉请求),在这种情况下,一切都按预期工作。如何对案例进行测试?您没有刷新$timeout-请尝试以下操作:
test('test', inject(function($http, $timeout) {
$httpBackend.when('GET', '/test').respond(500);
var promise = $http.get('/test');
$httpBackend.flush();
promise.then(
function(data) {
dump('success', data);
},
function(data) {
dump('error', data);
},
function(data) {
dump('notify', data);
}
);
// Timeout after we've attached notify listener.
$timeout.flush(1001);
}));
谢谢,非常有用,它在$timeout块中运行http请求,但我还无法获得notify承诺:(哦,可能是因为我告诉过你在添加then语句之前执行$timeout。请尝试我上面的编辑,将$timeout移到后面。这给了你一个附加notify回调的机会。你仍然会有错误回调,因为承诺被拒绝,但notify不起作用。请参阅我的编辑。我解决了问题,谢谢Peter!应该有used$rootScope.$digest()发送通知承诺,还有一篇关于测试$timeout的好文章
test('test', inject(function($http, $timeout) {
$httpBackend.when('GET', '/test').respond(500);
var promise = $http.get('/test');
$httpBackend.flush();
promise.then(
function(data) {
dump('success', data);
},
function(data) {
dump('error', data);
},
function(data) {
dump('notify', data);
}
);
// Timeout after we've attached notify listener.
$timeout.flush(1001);
}));