2017-04-04 63 views
1

我需要在处理完所有$ 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'); 
}]); 

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

我不能使用$q,因为$http我的页面调用属于各种指令,不在同一个控制器中调用。

+1

你可以使用'$ http.pendingRequests'。你可以检查$ http.pendingRequests.length!== 0; – talentedandrew

+1

你可以创建一个服务来保存所有这些$ http调用,因为$ http调用返回promise,这个服务是promise的集合,所以你只需要写如下:Promise.all(....) – ABOS

+0

@ABOS,我会阅读Promise.all()并尝试它。虽然会有问题回复你!谢谢。 – InquisitiveP

回答

0

您可以使用下面的代码来检查$ 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级范围内的变量,并用它作为计数器来保持成功的次数和失败您可以随时随地使用的呼叫。

+0

@talentedandrew - 这是我目前使用的。但是,没有办法知道我的任何通话是否失败。只有在成功完成所有$ http调用后,我才需要触发事件。 – InquisitiveP

+0

拦截器是找出失败和成功的呼叫数量的最佳方式。 – schaturv

+0

@InquisitiveP我已经更新了我的答案,以解决您的第二个问题。请看一看。 – schaturv

相关问题