AngularJS服务重试时的承诺被拒绝 [英] AngularJS service retry when promise is rejected

查看:194
本文介绍了AngularJS服务重试时的承诺被拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从一个异步的服务让我的控制器内的数据是这样的:

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

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
            // ???
        });
    }
}]);

我的问题:


  1. 当我得到的服务错误不返回的承诺如何再次查询服务。

  2. 它会更好做这在我的服务?

谢谢!

推荐答案

您可以重试在服务本身的要求,而不是控制。

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

因此​​, AsyncService.query 可以是这样的:

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;
      });
    }
  }
]);

这篇关于AngularJS服务重试时的承诺被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆