簡體   English   中英

如何知道所有$ http調用是否結束 - AngularJS

[英]How to know if all $http calls are over - AngularJS

我需要在處理所有$ 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調用屬於各種指令,並且不在同一個控制器中調用。

您可以使用以下代碼檢查$ 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個根作用域變量並將其用作計數器來維護成功和失敗調用的計數,您可以在任何地方使用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM