Angularjs 使用 $q.all 的微调控件

Angularjs spinner control using $q.all

我正在我的项目中实现微调器功能。黄金是在触发一个或多个 http 请求时显示微调器,并在请求成功时隐藏微调器。因为不知道先解决哪个请求,所以选择了$q.all。我有这样的指令:

angular.module('myApp', [])
  .directive('spinner', function($q, $http) {
    return {
      controller: function($scope) {
        $scope.showSpinner = true;
        var self = this;
        self.promises = [];

        self.makeHeader = function() {
          self.promises.push($http.get('some/url'));
          // Code that builds header goes here.
        };

        self.makeFooter = function() {
          self.promises.push($http.get('other/url'));
          // Code that builds footer goes here.
        };

        self.makeHeader();
        self.makeFooter();

        // Initial page load
        $q.all(self.promises).then(function() {
          // Hide the spinner.
          $scope.showSpinner = false;
        });
      }   
    }
  });

初始加载工作正常,但是当用户进行需要多次调用服务器的交互时,才能重建页眉和页脚。如何再次显示微调器并在承诺解决后将其隐藏?

您可以将重复调用包装到一个函数中。 我还建议将 2 个函数设为 return promise 而不是在内部处理 $http promise 以提供更大的灵活性。

angular.module('myApp', [])
  .directive('spinner', function($q, $http) {
    return {
      controller: function($scope) {
        var self = this;

        self.makeHeader = function() {
          return $http.get('some/url').then(function() {
            // Code that builds header goes here.
          });          
        };

        self.makeFooter = function() {
          return $http.get('other/url').then(function() {
            // Code that builds footer goes here.
          }); 
        };

        self.build = function() {
          $scope.showSpinner = true;
          self.promises = [];

          self.promises.push(self.makeHeader());
          self.promises.push(self.makeFooter());

          $q.all(self.promises).then(function() {
            // Hide the spinner.
            $scope.showSpinner = false;
          });
        }

        // initial run
        self.build();

        // subsequent call
        self.someClickHandler = function() {
          self.build();
        }

        // some other calls that need to use spinner
        self.other = function() {
          $scope.showSpinner = true;
          self.promises = [];

          self.promises.push(self.otherCall());

          $q.all(self.promises).then(function() {
            // Hide the spinner.
            $scope.showSpinner = false;
          });
        }
      }   
    }
  });

如您所见,如果每次都调用同一组函数,这种方法看起来会更好,但是如果您需要在其他情况下使用微调器,例如 self.other?

您可以将微调器包装在一个函数中并将其传递给 promise 数组。

var showSpinner = function(promises) {
  $scope.showSpinner = true;

  $q.all(promises).then(function() {
    // Hide the spinner.
    $scope.showSpinner = false;
  });
}

self.build = function() {
  var promises = [];

  promises.push(self.makeHeader());
  promises.push(self.makeFooter());

  showSpinner(promises);
}

self.other = function() {
  var promises = [];       
  promises.push(self.otherCall());

  showSpinner(promises);
}

看起来更干净了?