AngularJS:避免在收到响应之前调用两次相同的REST服务

时间:2015-01-15 21:43:47

标签: javascript angularjs http asynchronous q

我有两个指令,每个指令使用相同的工厂包装$ q / $ http。

angular.module("demo").directive("itemA", ["restService", function(restService) {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            restService.get().then(function(response) {
                // whatever
            }, function(response) {
               // whatever
            });
        }
    };
}]);


angular.module("demo").directive("itemB", ["restService", function(restService) {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            restService.get().then(function(response) {
                // whatever
            }, function(response) {
               // whatever
            });
        }
    };
}]);

angular.module("demo").factory("restService", ["$http", "$q", function($http, $q) {
    return {
       get: function() {
           var dfd = $q.defer();
           $http.get("whatever.json", {
               cache: true
           }).success(function(response) {
              // do some stuff here
              dfd.resolve(response);
           }).error(function(response) {
              // do some stuff here
              dfd.reject(response);
           });
       }
    };
}]);

问题:当我这样做时

<div item-a></div>
<div item-b></div>

我获得两次相同的Web服务,因为当ItemB的GET进行时,ItemA的GET仍在进行中。

有没有办法让第二个火灾知道已经有正在进行中的请求,以便它可以等一分钟并免费获取它?

我已经考虑过制作一个$ http或$ q封装器,将每个网址标记为待处理或不是,但我不确定这是最好的方法。如果有待处理,我该怎么办?只需返回现有的承诺,当其他承诺解决时它会解决吗?

1 个答案:

答案 0 :(得分:18)

是的,您需要做的就是在请求完成后缓存承诺并将其清除。中间的任何后续请求都可以使用相同的承诺。

angular.module("demo").factory("restService", ["$http", "$q", function($http, $q) {
    var _cache;
    return {
       get: function() {
          //If a call is already going on just return the same promise, else make the call and set the promise to _cache
          return _cache || _cache = $http.get("whatever.json", {
               cache: true
           }).then(function(response) {
              // do some stuff here
              return response.data;
           }).catch(function(response) {
              return $q.reject(response.data);
           }).finally(function(){
              _cache = null; //Just remove it here
           });
      }
   };
}]);