Nitin
Nitin

Reputation: 941

AngularJs loader while http request are ongoing on page

I have developed an application I want to add loader in my system as I see find BlockUI and make one demo but I have to kept it in every pages.

So is there any option there in angular that I can include it in one page and manage the flag from one place for all HTTP calls?

And it should remove only after all api calls are done.

Upvotes: 0

Views: 1292

Answers (2)

SteveL
SteveL

Reputation: 857

Not sure this is what you are wanting but based on the title - if someone is looking for a loader that is ridiculously easy to implement I've used loading bar

just include it in your app and it works automatically using interceptors.

angular.module('myApp', ['angular-loading-bar'])

Doesn't block the UI but does provide the loader. (Not sure from question which is the requirement?)

Upvotes: 1

Nitheesh
Nitheesh

Reputation: 19986

Just create a factory for $http calls and in that factory add listeners for the ajax load and end events. In that listeners add your loader show and hide events. Here is a sample code. Here I have used a google map service to get location and angular broadcast events to show and hide the loader.

<!doctype html>
<html ng-app="plunker">

<head>
    <meta charset="utf-8">
    <title>AngularJS Plunker</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script>
        var app = angular.module('plunker', []);

        app.config(function ($httpProvider) {

        });

        app.factory('httpPreConfig', ['$http', '$rootScope', function ($http, $rootScope) {
            $http.defaults.transformRequest.push(function () {
                console.log('Started');
                //Show your loader here
                $rootScope.$broadcast('AjaxProgress');
            });
            $http.defaults.transformResponse.push(function () {
                console.log('Stopped');
                //Hide your loader here
                $rootScope.$broadcast('AjaxFinished');
            })
            return $http;
        }]);

        app.controller('MainCtrl', function ($scope, $rootScope, httpPreConfig) {
            $scope.showLoader = false;
            $scope.sendGet = function () {
                httpPreConfig.get('http://maps.googleapis.com/maps/api/geocode/json?address=america');
            };
            
            $rootScope.$on('AjaxProgress', function(){
                $scope.showLoader = true;
            });
            
            $rootScope.$on('AjaxFinished', function(){
                $scope.showLoader = false;
            });
        });
    </script>
    
</head>

<body ng-controller="MainCtrl">
    <div ng-if="showLoader">Loader</div>
    <button ng-click="sendGet()">Send Get</button>
</body>

</html>

I hope this will be helpful for you.

Upvotes: 0

Related Questions