在多个$ http调用angularJs上显示微调器 [英] Show spinner on multiple $http calls angularJs
问题描述
这是交易。
我在做一个$ http调用时要显示一个微调器,但问题是我有多个调用,所以我在这里找到的例子没有帮助。
I what to show a spinner when doing a $http call, but the problem here is that I have multiple calls at ones, so the examples I found here didn't help.
有人有解决方案吗?
一种方式堆叠调用,以便微调器保持到最后一次调用结束?我希望能说明我的观点。
A way to stack the calls so the spinner remains until the last call finish? I hope to make my point.
我这样做。
angular.module('moduleName', []).
factory.("SomeService", function () {
return:{
getResources(params) {
/* do the $http call */
}
}
}).
controller("SomeCtrl", function (SomeService) {
SomeService.getResources(params)
}).
controller("OtherCtrl", function (SomeService) {
SomeService.getResources(params)
});
2个控制器可以同时调用该服务,并且可能会得到不同的响应。
The 2 controllers may call the service at the same time and the may get diferent responce.
推荐答案
Angular中的所有 $ http
调用都会返回一个承诺。
All $http
calls in Angular return a promise.
$ q
服务没有Q 库,但如果你看一下文档,它有一个所有
方法,可用于为您提供所需的功能。
The $q
service doesn't have all the bells and whistles of the Q library, which it is based, but if you look at the docs, it does have an all
method that can be used to give you the functionality you want.
以下是你如何使用它:
app.controller('HttpController', function($http, $q) {
// A hypothetical submit function
$scope.submit = function() {
// Set a loading variable for use in the view (to show the spinner)
$scope.loading = true;
var call1 = $http.get(/* ... */);
var call2 = $http.get(/* ... */);
var call3 = $http.get(/* ... */);
$q.all([call1, call2, call3]).then(function(responses) {
// responses will be an array of values the individual
// promises were resolved to. For this case, we don't
// need it, since we only care that they all resolved
// successfully.
$scope.loading = false;
}, function(errorValue) {
// If any of the promises is rejected, the error callback
// will be resolved with that rejection value, kind of like
// an early exit. We want to mark the loading variable
// as false here too, and do something with the error.
$scope.loading = false;
});
};
});
这篇关于在多个$ http调用angularJs上显示微调器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!