我有一些服务可以在多个控制器和工厂之间从服务器获取和共享数据提供程序。当我加载页面时,一些工厂可以调用相同的服务功能来获取服务器数据。它会对同一API资源生成多个HTTP调用。我有一个最小的控件来保存API数据到变量,转发调用使用这些数据。我希望避免这种情况。我可以做一个请求和其他数据请求等待完成第一个请求吗?
实际实施示例:
function getAllCategories() {
var deferred = $q.defer();
if (categoriesInitialized == 1) {
deferred.resolve(categories);
}
else {
categoriesInitialized = 0;
categoryApiMethods.getAll(function (result) {
for (var i = 0; i < result.length; i++) {
if (!checkCategoryExists(result[i]))
categories.push(new categoryModel(result[i]));
}
categoriesInitialized = 1;
deferred.resolve(categories);
}, function (data, status, header, config) {
//toaster.pop('error', data);
deferred.reject(data, status, header, config);
});
}
return deferred.promise;
}
答案 0 :(得分:1)
只需在逻辑中添加一个加载值,并保存一系列待处理的promises以在加载完成时解析。
function getAllCategories() {
var deferred = $q.defer();
if (!loading && categoriesInitialized == 1) {
deferred.resolve(categories);
}
else if (!loading) {
categoriesInitialized = 0;
loading = true;
categoryApiMethods.getAll(function (result) {
for (var i = 0; i < result.length; i++) {
if (!checkCategoryExists(result[i]))
categories.push(new categoryModel(result[i]));
}
categoriesInitialized = 1;
loading = false;
deferred.resolve(categories);
waiting.forEach(function(promise) {
promise.resolve(categories);
}
}, function (data, status, header, config) {
//toaster.pop('error', data);
deferred.reject(data, status, header, config);
waiting.forEach(function(promise) {
promise.reject(....);
}
});
} else {
waiting.push(deferred.promise);
}
return deferred.promise;
}