我正在构建我的第一个Angular应用程序,但我遇到了一个问题。我有一个AngularJS资源,其.get我调用成功和错误回调,如下所示:
var new_uptime = Uptime.get({}, function(){
console.log("new_uptime", new_uptime, "$scope.uptime", $scope.uptime);
console.log("new_uptime.uptime", new_uptime.uptime);
if ($scope.uptime && new_uptime.uptime < $scope.uptime.uptime) {
console.log("Reboot detected");
location.reload(true);
}
$scope.uptime = new_uptime;
$timeout(reload_uptime, 5000);
}, function(response){
console.log("Failed to read uptime", response);
console.log("Retrying in 10s");
$scope.uptime = "[unknown]";
$timeout(reload_uptime, 10000);
});
我已经使用服务器的各种错误状态测试了它,它运行正常。现在我想在503s上添加应用程序范围的重试。我为此添加了一个模块,如下所示:
retry_module = angular.module('service.retry', []);
retry_module.factory("retry", ["$q", "$injector", "$timeout", function($q, $injector, $timeout) {
return {
"responseError": function(rejection) {
console.log("Request failed", rejection);
if (rejection.status != 503) {
console.log("Unhandled status");
return $q.reject(rejection);
}
var delay = Math.floor(Math.random() * 1000);
console.log("Was 503, retrying in " + delay + "ms");
var deferred = $q.defer();
$timeout(function() {
var $http = $http || $injector.get("$http");
deferred.resolve($http(rejection.config));
}, delay);
return deferred;
}
};
}]);
retry_module.config(["$httpProvider", function ($httpProvider) {
$httpProvider.interceptors.push("retry");
}]);
这适用于在503s上重试,并且成功的尝试由Uptime.get调用者中的成功回调处理,如预期的那样。但是,如果服务器返回一些其他错误,那么我得到“未处理状态”打印输出,但是既没有“new_uptime”也没有“无法读取正常运行时间”。我的拒绝去了哪里,我该如何处理这样的问题?
答案 0 :(得分:2)
你需要退还承诺,而不是延期。所以responseError处理程序的结尾应该是:
var deferred = $q.defer();
$timeout(function() {
var $http = $http || $injector.get("$http");
deferred.resolve($http(rejection.config));
}, delay);
return deferred.promise;