【发布时间】:2015-11-26 06:01:05
【问题描述】:
我当前的实现有多个控制器使用服务访问同一个 JSON 数据集。我希望能够在单个查询中解决在进行中的 HTTP 请求期间传入的多个请求。
服务:
app.factory('dataService', function($http, $q) {
var promises = [];
var busy = false;
return {
getData: function() {
if (busy) {
var p = $q.defer();
promises.push(p);
return p.promise;
}
busy = true;
var promise = $http.get('data.json').then(function(response) {
while (promises.length > 0) {
promises.pop().resolve(response.data);
}
busy = false;
return response.data;
}, function(error) {
while (promises.length > 0) {
promises.pop().reject(error);
}
busy = false;
});
return promise;
}
}
});
控制器:
app.controller('Ctrl1', function($scope, dataService) {
$scope.logger = "";
function getIt(a) {
dataService.getData().then(function(d) {
$scope.logger += 'Request '+a+': '+(new Date).getTime()+'\n';
});
}
// These will be resolved in a 'batch'
getIt(1);
setTimeout(function(){getIt(2)},100);
setTimeout(function(){getIt(3)},0);
// This will be resolved in the 'next batch'
setTimeout(function(){getIt(4)},2000);
setTimeout(function(){getIt(5)},2100);
});
plunker 示例。
假设请求的顺序并不重要,有没有更好的方法来做到这一点,或者这种技术是否存在任何可能潜伏的缺陷?
【问题讨论】:
-
这样做有什么特殊原因,请求不是已经缓存在浏览器中了吗?
-
对不起,我的应用程序实际上并不要求静态 JSON,而是通过科尔多瓦的推送插件从角度广播中请求的实时数据馈送。显示的示例只是为了在具体实现中清晰
标签: javascript ajax angularjs promise