我正在使用AngularJS的$http服务来进行Ajax请求。
如何在Ajax请求执行时显示旋转GIF(或另一种类型的忙碌指示器)?
我在AngularJS文档中没有看到类似ajaxstartevent的东西。
我正在使用AngularJS的$http服务来进行Ajax请求。
如何在Ajax请求执行时显示旋转GIF(或另一种类型的忙碌指示器)?
我在AngularJS文档中没有看到类似ajaxstartevent的东西。
当前回答
加上@Adam的回答,
按照建议使用ng-show,但是,在您的情况下,您希望该功能具有多个请求,并在加载器被隐藏之前等待所有请求。
<span ng-show="pendingRequests > 0">
<img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" style="height:20px;"/>
</span>
然后在控制器中:
$scope.pendingRequests++;
let url = '/whatever_Your_URL_Is'
$http.get(url)
.then(function(response) {
$scope.pendingRequests--;
})
其他回答
如果你想为每个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>
这对我来说很管用:
HTML:
<div id="loader" class="ng-hide" ng-show="req.$$state.pending">
<img class="ajax-loader"
width="200"
height="200"
src="/images/spinner.gif" />
</div>
角:
$scope.req = $http.get("/admin/view/"+id).success(function(data) {
$scope.data = data;
});
当$http返回的承诺是未决的,ng-show将评估它是“真实的”。一旦承诺被解决,这将自动更新…这正是我们想要的。
只需使用ng-show和一个布尔值
不需要使用指令,不需要变得复杂。
下面是代码,可以放在提交按钮旁边,或者放在你想要旋转器的任何位置:
<span ng-show="dataIsLoading">
<img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" style="height:20px;"/>
</span>
然后在控制器中:
$scope.dataIsLoading = true
let url = '/whatever_Your_URL_Is'
$http.get(url)
.then(function(response) {
$scope.dataIsLoading = false
})
加上@Adam的回答,
按照建议使用ng-show,但是,在您的情况下,您希望该功能具有多个请求,并在加载器被隐藏之前等待所有请求。
<span ng-show="pendingRequests > 0">
<img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" style="height:20px;"/>
</span>
然后在控制器中:
$scope.pendingRequests++;
let url = '/whatever_Your_URL_Is'
$http.get(url)
.then(function(response) {
$scope.pendingRequests--;
})
如果你在一个服务/工厂中包装你的api调用,那么你可以跟踪那里的加载计数器(每个答案和@JMaylin的优秀同步建议),并通过一个指令引用加载计数器。或其任何组合。
API 包装器
yourModule
.factory('yourApi', ['$http', function ($http) {
var api = {}
//#region ------------ spinner -------------
// ajax loading counter
api._loading = 0;
/**
* Toggle check
*/
api.isOn = function () { return api._loading > 0; }
/**
* Based on a configuration setting to ignore the loading spinner, update the loading counter
* (for multiple ajax calls at one time)
*/
api.spinner = function(delta, config) {
// if we haven't been told to ignore the spinner, change the loading counter
// so we can show/hide the spinner
if (NG.isUndefined(config.spin) || config.spin) api._loading += delta;
// don't let runaway triggers break stuff...
if (api._loading < 0) api._loading = 0;
console.log('spinner:', api._loading, delta);
}
/**
* Track an ajax load begin, if not specifically disallowed by request configuration
*/
api.loadBegin = function(config) {
api.spinner(1, config);
}
/**
* Track an ajax load end, if not specifically disallowed by request configuration
*/
api.loadEnd = function (config) {
api.spinner(-1, config);
}
//#endregion ------------ spinner -------------
var baseConfig = {
method: 'post'
// don't need to declare `spin` here
}
/**
* $http wrapper to standardize all api calls
* @param args stuff sent to request
* @param config $http configuration, such as url, methods, etc
*/
var callWrapper = function(args, config) {
var p = angular.extend(baseConfig, config); // override defaults
// fix for 'get' vs 'post' param attachment
if (!angular.isUndefined(args)) p[p.method == 'get' ? 'params' : 'data'] = args;
// trigger the spinner
api.loadBegin(p);
// make the call, and turn of the spinner on completion
// note: may want to use `then`/`catch` instead since `finally` has delayed completion if down-chain returns more promises
return $http(p)['finally'](function(response) {
api.loadEnd(response.config);
return response;
});
}
api.DoSomething = function(args) {
// yes spinner
return callWrapper(args, { cache: true });
}
api.DoSomethingInBackground = function(args) {
// no spinner
return callWrapper(args, { cache: true, spin: false });
}
// expose
return api;
});
微调控制项指令
(function (NG) {
var loaderTemplate = '<div class="ui active dimmer" data-ng-show="hasSpinner()"><div class="ui large loader"></div></div>';
/**
* Show/Hide spinner with ajax
*/
function spinnerDirective($compile, api) {
return {
restrict: 'EA',
link: function (scope, element) {
// listen for api trigger
scope.hasSpinner = api.isOn;
// attach spinner html
var spin = NG.element(loaderTemplate);
$compile(spin)(scope); // bind+parse
element.append(spin);
}
}
}
NG.module('yourModule')
.directive('yourApiSpinner', ['$compile', 'yourApi', spinnerDirective]);
})(angular);
使用
<div ng-controller="myCtrl" your-api-spinner> ... </div>