[Solved] – Angularjs – How to show a loader gif during the ajax request?

Showing Spinner GIF during $http request in AngularJS

Asked on October 16, 2018 in AngularJs.
Add Comment


  • 6 Answer(s)

    AngularJS

    angular.module('SharedServices', [])
    
    .config(function ($httpProvider) {
    
    $httpProvider.responseInterceptors.push('myHttpInterceptor');
    
    var spinnerFunction = function (data, headersGetter) {
    
    // todo start the spinner here
    
    //alert('start spinner');
    
    $('#mydiv').show();
    
    return data;
    
    };
    
    $httpProvider.defaults.transformRequest.push(spinnerFunction);
    
    })
    
    // register the interceptor as a service, intercepts ALL angular ajax http calls
    
    .factory('myHttpInterceptor', function ($q, $window) {
    
    return function (promise) {
    
    return promise.then(function (response) {
    
    // do something on success
    
    // todo hide the spinner
    
    //alert('stop spinner');
    
    $('#mydiv').hide();
    
    return response;
    }, function (response) {
    
    // do something on error
    
    // todo hide the spinner
    
    //alert('stop spinner');
    
    $('#mydiv').hide();
    
    return $q.reject(response);
    
    });
    
    };
    
    });
    //regular angular initialization continued below....
    
    angular.module('myApp', [ 'myApp.directives', 'SharedServices']).
    
    //.......
    

    (HTML / CSS)

    $('#mydiv').show();
    
    $('#mydiv').hide();
    
    

    The above is utilized in the precise module at start of post.

    #mydiv {
    position:absolute;
    
    top:0;
    
    left:0;
    
    width:100%;
    
    height:100%;
    
    z-index:1000;
    
    background-color:grey;
    
    opacity: .8;
    
    }
    .ajax-loader {
    
    position: absolute;
    
    left: 50%;
    
    top: 50%;
    
    margin-left: -32px; /* -1 * image width / 2 */
    
    margin-top: -32px; /* -1 * image height / 2 */
    
    display: block;
    }
    <div id="mydiv">
    
    <img src="lib/jQuery/images/ajax-loader.gif" class="ajax-loader"/>
    
    </div>
    
    Answered on October 16, 2018.
    Add Comment

    This truly relies upon your particular utilize case, however a straightforward way would take after an example like this:

    .controller('MainCtrl', function ( $scope, myService ) {
    
    $scope.loading = true;
    
    myService.get().then( function ( response ) {
    
    $scope.items = response.data;
    
    }, function ( response ) {
    
    // TODO: handle the error somehow
    
    }).finally(function() {
    
    // called no matter success or failure
    
    $scope.loading = false;
    
    });
    
    });
    
    

    And then react to it in your template:

    <div class="spinner" ng-show="loading"></div>
    
    <div ng-repeat="item in items>{{item.name}}</div>
    
    
    Answered on October 16, 2018.
    Add Comment

    Utilized after intercepter to indicate stacking bar on http ask

    'use strict';
    
    appServices.factory('authInterceptorService', ['$q', '$location', 'localStorage','$injector','$timeout', function ($q, $location, localStorage, $injector,$timeout) {
    var authInterceptorServiceFactory = {};
    
    var requestInitiated;
    //start loading bar
    
    var _startLoading = function () {
    
    console.log("error start loading");
    
    $injector.get("$ionicLoading").show();
    }
    //stop loading bar
    
    var _stopLoading = function () {
    
    $injector.get("$ionicLoading").hide();
    
    }
    //request initiated
    
    var _request = function (config) {
    
    requestInitiated = true;
    
    _startLoading();
    
    config.headers = config.headers || {};
    
    var authDataInitial = localStorage.get('authorizationData');
    
    if (authDataInitial && authDataInitial.length > 2) {
    
    var authData = JSON.parse(authDataInitial);
    
    if (authData) {
    
    config.headers.Authorization = 'Bearer ' + authData.token;
    
    }
    
    }
    
    return config;
    
    }
    //request responce error
    
    var _responseError = function (rejection) {
    
    _stopLoading();
    
    if (rejection.status === 401) {
    
    $location.path('/login');
    
    }
    
    return $q.reject(rejection);
    
    }
    //request error
    
    var _requestError = function (err) {
    
    _stopLoading();
    
    console.log('Request Error logging via interceptor');
    
    return err;
    
    }
    //request responce
    
    var _response = function(response) {
    
    requestInitiated = false;
    // Show delay of 300ms so the popup will not appear for multiple http request
    
    $timeout(function() {
    if(requestInitiated) return;
    
    _stopLoading();
    
    console.log('Response received with interceptor');
    },300);
    return response;
    
    }
    authInterceptorServiceFactory.request = _request;
    
    authInterceptorServiceFactory.responseError = _responseError;
    
    authInterceptorServiceFactory.requestError = _requestError;
    
    authInterceptorServiceFactory.response = _response;
    return authInterceptorServiceFactory;
    
    }
    
    Answered on October 16, 2018.
    Add Comment

     

    Showing Spinner GIF during $http request in angularjs:

    .controller('MainCtrl', function ( $scope, myService ) {
      $scope.loading = true;
      myService.get().then( function ( response ) {
    $scope.items = response.data;
      }, function ( response ) {
    // TODO: handle the error somehow
    })  .finally(function() {
    // called no matter success or failure
      $scope.loading = false;
    });
    })
    
    <!--And then react to it in your template:-->
    <div class="spinner" ng-show="loading">
    <img src="http://w3lessons.info/demo/jquery-preloader/ajax-loader.gif" />
    </div>
    <div ng-repeat="item in items>{{item.name}}</div>
    
    
    .spinner { 
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #fefefe;
      z-index: 99;
      height: 100%;
      opacity: .8;
    }
    .spinner img {
      position: absolute;
      left: 50%;
      top: 50%; 
      margin-left: -32px; /* -1 * image width / 2 */
      margin-top: -32px; /* -1 * image height / 2 */
      display: block; 
    }
    
    Answered on December 19, 2018.
    Add Comment

    If you are using ngResource, the $resolved attribute of an object is useful for loaders:

    For a resource as follows:

    var User = $resource('/user/:id', {id:'@id'});
    var user = User.get({id: 1})

    You can link a loader to the $resolved attribute of the resource object:

    <div ng-hide="user.$resolved">Loading ...</div>

     

    Answered on January 18, 2019.
    Add Comment

    Here are the current past AngularJS incantations:

    angular.module('SharedServices', [])
        .config(function ($httpProvider) {
            $httpProvider.responseInterceptors.push('myHttpInterceptor');
            var spinnerFunction = function (data, headersGetter) {
                // todo start the spinner here
                //alert('start spinner');
                $('#mydiv').show();
                return data;
            };
            $httpProvider.defaults.transformRequest.push(spinnerFunction);
        })
    // register the interceptor as a service, intercepts ALL angular ajax http calls
        .factory('myHttpInterceptor', function ($q, $window) {
            return function (promise) {
                return promise.then(function (response) {
                    // do something on success
                    // todo hide the spinner
                    //alert('stop spinner');
                    $('#mydiv').hide();
                    return response;
    
                }, function (response) {
                    // do something on error
                    // todo hide the spinner
                    //alert('stop spinner');
                    $('#mydiv').hide();
                    return $q.reject(response);
                });
            };
        });
    
    //regular angular initialization continued below....
    angular.module('myApp', [ 'myApp.directives', 'SharedServices']).
    //.......

    Here is the rest of it (HTML / CSS)….using

    $('#mydiv').show(); 
    $('#mydiv').hide(); 

    to toggle it. NOTE: the above is used in the angular module at beginning of post

    #mydiv {  
        position:absolute;
        top:0;
        left:0;
        width:100%;
        height:100%;
        z-index:1000;
        background-color:grey;
        opacity: .8;
     }
    
    .ajax-loader {
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -32px; /* -1 * image width / 2 */
        margin-top: -32px;  /* -1 * image height / 2 */
        display: block;     
    }
    
    <div id="mydiv">
        <img src="lib/jQuery/images/ajax-loader.gif" class="ajax-loader"/>
    </div>
    Answered on February 9, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.