我有一个有几个控制器的角形js项目,每个控制器我使用这么多api调用,这需要很长时间,所以我想在每个页面调用api时将加载旋转放入其中。
我想保留一个根范围变量,如
$rootScope.showLoading=false;当我从任何控制器中生成这个变量时,比如
$rootScope.showLoadin=true; 那么旋转就会到来,当我使它变假的时候,旋转就会消失。
是怎么完成的?
发布于 2016-10-04 06:34:11
您可以为您的应用程序提出的每一个http请求应用加载程序,跟踪活动和解析请求的数量。因此,对于每个请求,xhrCreations由1添加,而对于每个已解析的xhrResolutions,则由1添加。
因此,如果活动请求的数量超过解析量,服务将被更新为true值。然后,当没有任何请求处于活动状态时,服务将使用false进行更新。因此,由于scope变量设置为false,所以将加载程序隐藏在控制器中。
core.factory('httpInterceptor', ['$q', 'globalStates', function ($q, globalStates) {
var xhrCreations = 0,
xhrResolutions = 0;
function isLoading() {
return xhrResolutions < xhrCreations;
}
return {
request: function (req) {
xhrCreations++;
globalStates.set('isRequestActive', isLoading());
return req;
},
requestError: function (err) {
xhrResolutions++;
globalStates.set('isRequestActive', isLoading());
return $q.reject(err);
},
response: function (res) {
xhrResolutions++;
globalStates.set('isRequestActive', isLoading());
return res;
},
responseError: function (err) {
xhrResolutions++;
globalStates.set('isRequestActive', isLoading());
return $q.reject(err);
}
};
}]);服务:
core.service('globalStates', [function() {
var gs = this;
var states = {};
gs.set = function(k, v) {
states[k] = v;
};
gs.get = function(k) {
return k ? states[k] : states;
};
}]);然后,您可以通过来自核心控制器的观察者访问服务中的值:
$scope.$watch(function() {
return globalStates.get();
}, function(states) {
$rootScope.showLoading = states.isLoading;
});https://stackoverflow.com/questions/39845559
复制相似问题