Angularjs 重新启动资源的加载指示器
我想创建一个加载指示器,就像一个小旋转器,简单地指示我的angular应用程序当前正在从服务器加载内容 我正在使用restanglar作为我的资源,它会为请求返回承诺 我的想法如下:创建一个服务,让Restanglar的承诺得以实现。检查是否所有承诺都已解决,并使用$q.all将加载设置为false 现在我想添加一个指令,该指令将传递给加载变量,并根据loading=true/false显示一个微调器 我创建了一个plunkr来说明这个想法: 我有一些问题: 如何拦截承诺而不在每个请求资源的指令中添加服务? addPromise函数中的回调函数被调用两次,这应该没有问题,因为它可能触发更改事件 传递的加载值不反映服务内的更改 下面是来自plunkr的代码:Angularjs 重新启动资源的加载指示器,angularjs,restangular,Angularjs,Restangular,我想创建一个加载指示器,就像一个小旋转器,简单地指示我的angular应用程序当前正在从服务器加载内容 我正在使用restanglar作为我的资源,它会为请求返回承诺 我的想法如下:创建一个服务,让Restanglar的承诺得以实现。检查是否所有承诺都已解决,并使用$q.all将加载设置为false 现在我想添加一个指令,该指令将传递给加载变量,并根据loading=true/false显示一个微调器 我创建了一个plunkr来说明这个想法: 我有一些问题: 如何拦截承诺而不在每个请求资源的指令
angular.module('myApp', ['restangular']);
angular.module('myApp').factory('LoadingService', ['$q' , function ($q) {
var promises = [];
var loading = false;
function addPromise(promise) {
promises.push(promise);
loading = true;
var allPromises = $q.all(promises);
allPromises.then(function() {
promises = [];
loading = false;
console.log('finished loading');
});
console.log('loading');
}
return {
addPromise : addPromise,
isLoading : loading
};
}]);
angular.module('myApp').directive('loadingIndicator', ['LoadingService', function(LoadingService) {
return {
restrict : 'E',
scope : {},
template : '<i ng-show="loading" class="glyphicon glyphicon-refresh" />',
link : function (scope) {
scope.loading = LoadingService.isLoading;
}
};
}]);
angular.module('myApp').directive('someDirective', ['LoadingService', 'Restangular', function(LoadingService, Restangular) {
function someDirectiveController ($scope, $q, Restangular) {
var promise = Restangular.one('dummy').getList();
LoadingService.addPromise(promise);
}
return {
restrict : 'E',
scope : {},
template : '<div>I am a directive loading some stuff</div>',
controller: ['$scope', '$q', 'Restangular', function($scope, $q, Restangular) {
return someDirectiveController($scope, $q, Restangular);
}]
};
}]);
为此,我只需要使用requestInterceptor开始加载,并使用responseInterceptor和errorInterceptor停止加载,就这样:。有了它,您可以获得这种加载行为:,但这不是只对单个资源有效吗?在plunker中,我同时加载了一些资源,因此指示器应该只停止显示所有承诺是否兑现,我目前一次加载大约10种不同的资源。我想知道的另一件事是拦截器在哪里,它们是应用程序范围内的吗?因为我创建了customer restangular对象,用于使用laravel php Framework进行分页。如果您同时加载多个,只需在requestInterceptor中设置一个计数器,并在responseInterceptor和error上减少它。若响应或错误时计数器变为0,则结束加载。