Shabeeb Ck
Shabeeb Ck

Reputation: 73

How to make a loading (spin) while requesting to server by $http on angularJS

$http({
      method: 'POST',
      url: '',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
      data: {
      }
      }).then(function successCallback(response) {
          // this callback will be called asynchronously
          // when the response is available

        if(response.data == 'true'){
            swal("Good job!", "New case has been created", "success");
        }
    }, function errorCallback(response) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });

I want to show a progress bar or spin on bootstrap while http request on angularjs

Upvotes: 1

Views: 466

Answers (2)

Aravind
Aravind

Reputation: 41571

Sugessting you to use this angular-loading-bar

Steps

  1. Include the script references and css as mentioned in the above github, you can use cdn as well as mentioned.

  2. Add these two functions in your controller

    $scope.start = function() {
      cfpLoadingBar.start();
    };
    
    $scope.complete = function () {
       cfpLoadingBar.complete();
    }
    
  3. Include the 'angular-loading-bar', 'ngAnimate' as dependencies.

  4. Add the below code for the app configurations

    • If you are looking for the progress bar

      app.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
         cfpLoadingBarProvider.includeSpinner = false;
      }])
      
    • If you are looking for a spinner

      app.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
         cfpLoadingBarProvider.includeSpinner = true;
      }])
      
  5. Finally, In your $http request call the $scope.start() function and in your success method call the $scope.complete()

LIVE DEMO

Upvotes: 1

Thierry
Thierry

Reputation: 5243

A simple way:

html:

<div class="spinner" ng-show="loading"></div>

js :

$scope.loading = true
$http.post(...).then(function(response){
  $scope.data = response.data // or whatever you needs...
  $scope.loading = false
},function(){
  $scope.loading = false
  console.log("error")
})

If you want to generalize, you can also have a look to http interceptor : https://docs.angularjs.org/api/ng/service/$http#interceptors

Upvotes: 1

Related Questions