我使用angular.js从两个Web服务加载两部分数据,我需要匹配两个数据集。
angular.js中的两部分数据被描述为
$scope.myorders = [];
$scope.catalogs = [];
$http({
url: baseURL + "data",
}).success(function (data, status, headers, config) {
$scope.myorders = data;
})
// match two datasets
_.each($scope.myorders, function( order){
_.each($scope.catalogs, function( catalog){
})
})
但是,有时匹配操作不一致,只加载一个数据集而未加载另一个数据集。
如何同步两个数据集以确保在两个数据集全部加载完毕后执行匹配操作
更新: 我试过这种方式
var deferred1 = $q.defer();
var deferred2 = $q.defer();
$http({
url: baseURL + "data",
}).success(function (data, status, headers, config) {
$scope.myorders = data;
console.log("deferred1.resolve");
deferred1.resolve();
})
$http({
url: baseURL + "data2",
}).success(function (data, status, headers, config) {
$scope.catalogs = data;
console.log("deferred2.resolve");
deferred2.resolve();
})
$q.all([
deferred1,
deferred2
])
.then(function(values) {
console.log("all resolved");
return values;
});
我试过这种方式,但是猜测它不对,因为输出序列不是我期望的
"all resolved"
"deferred2.resolve"
"deferred1.resolv"
如何解决这个问题?
答案 0 :(得分:2)
当2个http调用就绪时,你应该使用angular $q.all来解析数据
示例此处fiddle
对于每个调用,你应该创建deferred对象将其推入数组然后使用
$q.all(deferesArray).then(
function(resp){
// all requests are resolver , resp is array with resolved datas
}
)
在你的代码中你应该这样做
var deferred1 = $q.defer(); var deferred2 = $q.defer();
$http({
url: baseURL + "data",
}).success(function (data, status, headers, config) {
$scope.myorders = data;
console.log("deferred1.resolve");
deferred1.resolve(data);
})
$http({
url: baseURL + "data2",
}).success(function (data, status, headers, config) {
$scope.catalogs = data;
console.log("deferred2.resolve");
deferred2.resolve(data);
})
$q.all([ deferred1, deferred2 ]) .then(function(values) {
// your resolved values in this inside in this values variable
//
console.log("RESOLVED WITH VALUES",values);
// and you should run your logical functions here
// remember your values inside values array variable
// match two datasets
_.each(values[0], function( order){
_.each(values[1], function( catalog){
})
});
答案 1 :(得分:1)
要从延期中获取promise,您必须在其上调用deferred1.promise
。例如$q.all([deferred1.promise, deferred2.promise]);
但是由于$http
已经返回了一个承诺,你可以执行以下操作:
var urls = ["example.com/foo", "example.com/bar"];
var results = [];
var promises = urls.map(function(url){
return $http({
method: "GET",
url: url
})
.then(function(res){ //we probably also want to get each result
results.push(res);
});
});
$q.all(promises).then( function(lastvalue) {
console.log(results);
}, function(err) {
console.error(err);
});