Angular js - 检测所有 $http() 何时完成 [英] Angular js - detect when all $http() have finished

查看:26
本文介绍了Angular js - 检测所有 $http() 何时完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我在应用程序代码周围有大量的 $http() 调用,

Ok i have tons of $http() calls all around the app code,

我想知道有什么方法/最佳实践可以检测应用程序周围的所有 $http() 何时完成(成功/错误与返回什么无关,只需要知道如果完成)?

i'm wondering is there any way / best practice to detect when all $http() around the app have finished ( success/error donesn't matter what they return, just need to know if finished )?

这样我就可以在加载之前显示加载 gif 吗?

So that i can show a loading gif until they are loading ?

谢谢

推荐答案

这样做:

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 的事件(最好在指令中使用):

Then use event bound to $rootScope anywhere (preferable to use in directive):

$rootScope.$on('loading:progress', function (){
    // show loading gif
});

$rootScope.$on('loading:finish', function (){
    // hide loading gif
});

这篇关于Angular js - 检测所有 $http() 何时完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆