Show progress circular during $http post?

All we need is an easy explanation of the problem, so here it is.

What is the best way to use Angular Material’s Progress circular component with a $http request?

I currently have the code like this below:

Progress circular:

<md-progress-circular ng-if="determinateValue === 100" md-mode="determinate" value="{{determinateValue}}"></md-progress-circular>

$http request:

$scope.determinateValue = 0;

$http.get("/posts")
       .success(function (data) {

          $scope.posts = data;
          $scope.determinateValue = 100;

       })

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If you want a version of md-progress-circular that also inhibits the screen and has a backdrop place the md-progress-circular inside an mdDialog like this:

     function showWait(){
          $mdDialog.show({
            controller: 'waitCtrl',
            template: '<md-dialog style="background-color:transparent;box-shadow:none">' +
                        '<div layout="row" layout-sm="column" layout-align="center center" aria-label="wait">' +
                            '<md-progress-circular md-mode="indeterminate" ></md-progress-circular>' +
                        '</div>' +
                     '</md-dialog>',
            parent: angular.element(document.body),
            clickOutsideToClose:false,
            fullscreen: false
          })
          .then(function(answer) {

          });
   }

here is a plunker i created that shows how
Plunker

Method 2

I don’t think you need the value attribute here with determinate mode. Instead you should use indeterminate mode, then show and hide the progress indicator using ngShow.

<md-progress-circular md-mode="indeterminate" ng-show="isLoading"></md-progress-circular>

And in your JS

$scope.isLoading = true;
$http.get("/posts")
   .success(function (data) {
        $scope.isLoading = false;
   });

Method 3

All answers are right just add one more thing that $http request is asynchronous you should use like this

$scope.$apply(function(){
$scope.isLoading = false;
});

And as whole like this

<md-progress-circular md-mode="indeterminate" ng-show="isLoading"></md-progress-circular>

And in your JS

$scope.isLoading = true;

$http.get("/posts")
   .success(function (data) {
         $scope.$apply(function(){
           $scope.isLoading = false;
         });
   });

Note:- Source of the answer is the accepted answer.

Method 4

You should hook up to $httpProvider‘s events:

angular.module('common')
  .config(['$httpProvider', function($httpProvider){
    $httpProvider.interceptors.push(['$rootScope', '$q', '$timeout',
      function($rootScope, $q, $timeout) {
        return {
          request: function(config) {
            $rootScope.posting = new Date().getTime();
            $rootScope.$broadcast('$postingStart', config.url);
            return $q.resolve(config);
          },
          response: function(response) {
            $rootScope.posting = false;
            $rootScope.$broadcast('$postingEnd', response.config.url);
            return $q.resolve(response);
          },
          responseError: function(response) {
            $rootScope.posting = false;
            $rootScope.$broadcast('$postingEnd', response.config.url);
            return $q.reject(response);
          }
        };
      }]);
  }])
.run(['$mdDialog', '$rootScope', function($mdDialog, $rootScope){
  var showing = false;

  function showWait() {
    if(showing) return;
    $mdDialog.show({
      controller: 'waitCtrl',
      template: '<md-dialog id="plz_wait" style="background-color:transparent;box-shadow:none">' +
      '<div layout="row" layout-sm="column" layout-align="center center" aria-label="wait">' +
      '<md-progress-circular md-mode="indeterminate" ></md-progress-circular>' +
      '</div>' +
      '</md-dialog>',
      parent: angular.element(document.body),
      clickOutsideToClose: false,
      fullscreen: false
    })
      .then(function(answer) {
        showing = false;
      });
  }


  $rootScope.$on('$postingStart', function(event, url) {
    if (!$rootScope.postingStartTimer) {
      $rootScope.postingStartTimer = $timeout(function() {
        showWait()
      }, 250);
    }
  });

  $rootScope.$on('$postingEnd', function(event, url) {
    if ($rootScope.postingStartTimer && posts.length === 0) {
      $timeout.cancel($rootScope.postingStartTimer);
      $rootScope.postingStartTimer = false;
      if(!showing) return;
      $mdDialog.cancel();
    }
  });

}])

Method 5

I hope this code helps.

  var isLoadingShown = false;

  $scope.$watch(function() {
    return $http.pendingRequests.length;
  }, 
  function(newValue, oldValue) {
    console.log(newValue);
    if(newValue !== 0) {
      if(!isLoadingShown) {
        showLoading();         
      }
    }
    else hideLoading();
  });

  function showLoading(){
    isLoadingShown = true;   
    $mdDialog.show({
      template: '<md-dialog style="background-color:transparent;box-shadow:none;overflow: hidden !important;">' +
                  '<div layout="row" layout-sm="column" layout-align="center center" aria-label="wait">' +
                    '<md-progress-circular class="md-hue-2" md-diameter="50px"></md-progress-circular>' +
                  '</div>' +
                '</md-dialog>',
      parent: angular.element(document.body),
      clickOutsideToClose:false,
      escapeToClose: false,
      fullscreen: false
    });
  }

  function hideLoading(){
    $mdDialog.cancel();
    isLoadingShown = false; 
  }

Method 6

First set some model:

$scope.loading=false;

Bind that model with progress circular element ng-show property:

<md-progress-circular ng-show="loading" md-mode="indeterminate"></md-progress-circular>

Set it to true before calling $http request and set it to false on $http .success:

$scope.loading=true;

$http.get("/posts")
   .success(function (data) {

      $scope.posts = data;

      $scope.loading=false;

   })

Hope that helps.

Method 7

If you want to watch the progress of post data use uploadEventHandlers

There is an example.

$http({
    method: 'POST',
    url: '/uploadToFtp',
    headers: {
        'Content-Type': undefined
    },
    eventHandlers: {
        progress: function(c) {
            //console.log('Progress -> ' + c);
            //console.log(c);
        }
    },
    uploadEventHandlers: {
        progress: function(e) {
            //console.log('UploadProgress -> ' + e);
            //console.log(e);
            _self.progressValue = (e.loaded / e.total) * 100.0;
        }
    },
    data: postData,
    transformRequest: angular.identity
})
.then(callBack,errorCallBack)
.catch(errorCallBack);

Show the progress circular like this

<md-progress-circular ng-if="ctrl.progressValue > 0 && ctrl.progressValue < 100" md-mode="determinate" value="{{ctrl.progressValue}}"></md-progress-circular>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply