我从控制器内部的异步服务获取数据,如下所示:
myApp.controller('myController', ['$scope', 'AsyncService', function($scope, AsyncService) { $scope.getData = function(query) { return AsyncService.query(query).then(function(response) { // Got success response, return promise return response; }, function(reason) { // Got error, query again in one second // ??? }); } }]);
我的问题:
谢谢!
您可以在服务本身而不是控制器中重试该请求。
因此,AsyncService.query可能是这样的:
AsyncService.query
AsyncService.query = function() { var counter = 0 var queryResults = $q.defer() function doQuery() { $http({method: 'GET', url: 'https://example.com'}) .success(function(body) { queryResults.resolve(body) }) .error(function() { if (counter < 3) { doQuery() counter++ } }) } return queryResults.promise }
您可以摆脱控制器中的错误功能:
myApp.controller('myController', ['$scope', 'AsyncService', function($scope, AsyncService) { $scope.getData = function(query) { return AsyncService.query(query).then(function(response) { // Got success response return response; }); } } ]);