我需要在处理完我的所有 $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/