I'm building my first Angular app, and I've run into a problem. I have an AngularJS resource whose .get I call with both a success and error callback, like so:
我正在构建我的第一个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);
});
I've tested this with various error statuses from the server, and it works fine. Now I'd like to add app-wide retrying on 503s. I've added a module for that, which looks like this:
我已经使用服务器的各种错误状态对此进行了测试,并且工作正常。现在我想在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");
}]);
This works well for retrying on 503s, and successful attempts are handled by the success callback in the Uptime.get caller, as intended. However, if the server returns some other error, then I get the "Unhandled status" printout, but then neither "new_uptime" nor "Failed to read uptime". Where did my rejection go, and how do I go about trouble-shooting issues like this?
这适用于在503s上重试,并且成功的尝试由Uptime.get调用者中的成功回调处理,如预期的那样。但是,如果服务器返回其他一些错误,那么我会得到“未处理状态”打印输出,但后来既没有“new_uptime”也没有“无法读取正常运行时间”。我的拒绝去了哪里,我该如何处理这样的问题?
1 个解决方案
#1
2
You need to return the promise, not the deferred. So the end of your responseError handler should be:
你需要退还承诺,而不是延期。所以responseError处理程序的结尾应该是:
var deferred = $q.defer();
$timeout(function() {
var $http = $http || $injector.get("$http");
deferred.resolve($http(rejection.config));
}, delay);
return deferred.promise;
#1
2
You need to return the promise, not the deferred. So the end of your responseError handler should be:
你需要退还承诺,而不是延期。所以responseError处理程序的结尾应该是:
var deferred = $q.defer();
$timeout(function() {
var $http = $http || $injector.get("$http");
deferred.resolve($http(rejection.config));
}, delay);
return deferred.promise;