javascript - 如何知道所有 $http 调用是否结束 - AngularJS

标签 javascript angularjs http

我需要在处理完我的所有 $http 调用后触发一个事件。我还需要知道是否有任何调用失败。我尝试使用 stackoverflow 上的可用解决方案,例如使用拦截器。

angular.module('app').factory('httpInterceptor', ['$q', '$rootScope',
  function ($q, $rootScope) {
    var loadingCount = 0;

    return {
      request: function (config) {
        if(++loadingCount === 1) {
          $rootScope.$broadcast('loading:progress');
        }
        return config || $q.when(config);
      },    
      response: function (response) {
        if(--loadingCount === 0) {
          $rootScope.$broadcast('loading:finish');
        }
        return response || $q.when(response);
      },    
      responseError: function (response) {
        if(--loadingCount === 0) {
          $rootScope.$broadcast('loading:finish');
        }
        return $q.reject(response);
      }
    };
  }
]).config(['$httpProvider', function ($httpProvider) {
  $httpProvider.interceptors.push('httpInterceptor');
}]);

但是,通过这种方法,$rootScope.$broadcast('loading:finish') 在每个 $http 调用完成后被调用。我想在所有 $http 调用结束时触发一个事件。

我不能使用 $q,因为我页面中的 $http 调用属于不同的指令,而不是在同一个 Controller 中调用。

最佳答案

您可以使用下面的代码来检查 $http 的未决请求数。我正在使用它来显示我的项目中的加载微调器。

$http.pendingRequests.length

要跟踪失败和成功的调用,您可以使用如下方法:

angular.module('myApp', [])
.run(function ($rootScope){
  $rootScope.failedCalls = 0;
  $rootScope.successCalls = 0;
 })
.controller('MyCtrl', 
function($log, $scope, myService) {
 $scope.getMyListing = function(employee) {
   var promise = 
       myService.getEmployeeDetails('employees');
   promise.then(
      function(payload) { 
          $scope.listingData = payload.data;
          $rootScope.successCalls++; //Counter for success calls
      },
      function(errorPayload) {
        $log.error('failure loading employee details', errorPayload);
        $rootScope.failedCalls++; //Counter for failed calls
      });
 };
 })
 .factory('myService', function($http) {
  return {
  getEmployeeDetails: function(id) {
     return $http.get('/api/v1/employees/' + id);
  }
}
 });

基本上我已经创建了 2 个根作用域变量并将其用作计数器来维护成功和失败调用的计数,您可以在任何地方使用它们。

关于javascript - 如何知道所有 $http 调用是否结束 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43205459/

相关文章:

javascript - 使用 Express/MongoDB 构建收件箱系统

javascript - 如何根据所选的下拉值更改表单值操作

javascript - 加载所有 Tiles 时的 MapBox 事件

javascript - html 中可重复代码的可重用性

c# - 如何防止我的 HTTP 服务器出现 "sleeping"?

html - 如何将消息发送到 OpenID URL..?

javascript - 从 datetimepicker bootstrap 上点击的日期获取点击事件

javascript - 如何使用 Angular $location 通过动态更改其键值参数来设置我的新 url 位置?

javascript - ng-bind-html 不起作用

android - 无法从模拟器联系主机 (10.0.2.2)