Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular js - detect when all $http() have finished

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

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 )?

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

thanks

like image 725
itsme Avatar asked Apr 29 '14 10:04

itsme


2 Answers

Do it like this:

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');
}]);

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
});
like image 71
karaxuna Avatar answered Nov 08 '22 14:11

karaxuna


It is possible if you execute all requests by $q.all

$scope.request1 = $http.get('request1URL', {cache: false});
$scope.request2 = $http.get('request2URL', {'cache': false});
$scope.loading = true;

$q.all([$scope.request1, $scope.request2]).then(function(values) {
     $scope.loading = false;
     // Do whatever you want
     // values[0], values[1]
});

Using ng-if, you can show and hide loading gif.

In case, if you use different $http call, then have a count or array in the $rootScope and update them whenever $http complete. Based on the count or array.length enable the loading gif.

like image 10
Fizer Khan Avatar answered Nov 08 '22 13:11

Fizer Khan