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

AngularJS: Avoid calling same REST service twice before response is received

本文关键字:服务 REST 两次 调用 响应 AngularJS      更新时间:2023-09-26

我有两个指令,每个指令使用相同的工厂包装$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包装器,将每个 URL 标记为待处理或不挂起,但我不确定这是最好的方法。 如果它处于待处理状态,我该怎么办? 只需返回现有承诺,当另一个解决时它会解决?

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

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