我正在使用AngularJS的$http服务来进行Ajax请求。

如何在Ajax请求执行时显示旋转GIF(或另一种类型的忙碌指示器)?

我在AngularJS文档中没有看到类似ajaxstartevent的东西。


当前回答

使用拦截器来显示http请求上的加载条

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

其他回答

如果我们知道DRY的概念,那么所有的答案都是复杂的,或者需要在每个请求上设置一些变量,这是非常错误的做法。这里是一个简单的拦截器的例子,当ajax启动时,我将鼠标设置为等待,当ajax结束时设置为自动。

$httpProvider.interceptors.push(function($document) {
    return {
     'request': function(config) {
         // here ajax start
         // here we can for example add some class or show somethin
         $document.find("body").css("cursor","wait");

         return config;
      },

      'response': function(response) {
         // here ajax ends
         //here we should remove classes added on request start

         $document.find("body").css("cursor","auto");

         return response;
      }
    };
  });

代码必须添加到应用程序配置app.config中。我展示了如何改变鼠标加载状态,但在那里,它是可以显示/隐藏任何加载器内容,或添加,删除一些css类显示加载器。

拦截器将在每次ajax调用上运行,因此不需要创建特殊的布尔变量($scope. js)。加载=true/false等)在每个HTTP调用。

如果你想为每个HTTP请求调用显示加载器,那么你可以使用angular interceptor来管理HTTP请求调用。

下面是一个示例代码

<body data-ng-app="myApp">
<div class="loader">
    <div id="loader"></div>
</div>

<script>
    var app = angular.module("myApp", []);

    app.factory('httpRequestInterceptor', ['$rootScope', '$location', function ($rootScope, $location) {
        return {
            request: function ($config) {
                $('.loader').show();
                return $config;
            },
            response: function ($config) {
                $('.loader').hide();
                return $config;
            },
            responseError: function (response) {
                return response;
            }
        };
    }]);

    app.config(['$stateProvider', '$urlRouterProvider', '$httpProvider',
        function ($stateProvider, $urlRouterProvider, $httpProvider) {
            $httpProvider.interceptors.push('httpRequestInterceptor');
        }]);

</script>
</body>

https://github.com/wongatech/angular-http-loader是一个很好的项目。

例如http://wongatech.github.io/angular-http-loader/

下面的代码显示了发生请求时的模板示例/loader.tpl.html。

<div ng-http-loader template="example/loader.tpl.html"></div>

下面是我的实现,就像ng-show和请求计数器一样简单。

它使用一个新的服务为所有请求$http:

myApp.service('RqstSrv', [ '$http', '$rootScope', function($http, $rootScope) {
    var rqstService = {};

    rqstService.call = function(conf) {

        $rootScope.currentCalls = !isNaN($rootScope.currentCalls) ?  $rootScope.currentCalls++ : 0;

        $http(conf).then(function APICallSucceed(response) {
            // Handle success
        }, function APICallError(response) {
            // Handle error
        }).then(function() {
            $rootScope.currentCalls--;
        });
    }
} ]);

然后你可以根据当前调用的数量使用你的加载器:

<img data-ng-show="currentCalls > 0" src="images/ajax-loader.gif"/>

刚刚发现了angular-busy指令,它显示了一个依赖于某些异步调用的小加载器。

例如,如果你必须创建一个GET,在$作用域中引用承诺,

$scope.req = $http.get('http://google.fr');

像这样称呼它:

<div cg-busy="req"></div>

这是GitHub。

你也可以使用bower安装它(别忘了更新你的项目依赖项):

bower install angular-busy --save