我需要在处理完所有$ 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
我的页面调用属于各种指令,不在同一个控制器中调用。
你可以使用'$ http.pendingRequests'。你可以检查$ http.pendingRequests.length!== 0; – talentedandrew
你可以创建一个服务来保存所有这些$ http调用,因为$ http调用返回promise,这个服务是promise的集合,所以你只需要写如下:Promise.all(....) – ABOS
@ABOS,我会阅读Promise.all()并尝试它。虽然会有问题回复你!谢谢。 – InquisitiveP