AngularJS service retry when promise is rejected

后端 未结 5 2227
Happy的楠姐
Happy的楠姐 2020-12-13 11:06

I\'m getting data from an async service inside my controller like this:

myApp.controller(\'myController\', [\'$scope\', \'AsyncService\',
function($scope, As         


        
5条回答
  •  不知归路
    2020-12-13 11:13

    You can retry the request in the service itself, not the controller.

    So, AsyncService.query can be something like:

    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
    }
    

    And you can get rid of your error function in the controller:

    myApp.controller('myController', ['$scope', 'AsyncService',
      function($scope, AsyncService) {
        $scope.getData = function(query) {
          return AsyncService.query(query).then(function(response) {
            // Got success response
            return response;
          });
        }
      }
    ]);
    

提交回复
热议问题