我有这段代码:
// HTTP request
$http.get(dataSource).
then(function(data, status, headers, config) {
// Products array
var products = [];
// Loop through each array value
for (var slug in data.data){
var product = data.data[slug];
$http.get('content/products/' + product + '.json').then(function(response){
products.push(response.data);
$scope.products = products;
}).catch(function(){
console.log('there was an error');
});
}
}).catch(function(){
console.log('there was an error');
});
问题在于,有时产品范围数组项不会始终按照请求的顺序到达。
我需要产品$ scope来循环遍历数组,并且只有在响应被推送到数组时:
products.push(response.data);
最终分配给变量$scope.products
。
有关修改当前HTTP请求的任何帮助吗?
答案 0 :(得分:1)
问题在于for循环,即同步,包含异步代码。实际上,无法保证内部http.get按照获得的顺序处理数据。
试试这个:
// HTTP request
$http.get(dataSource).
then(function(data, status, headers, config) {
// Products array
var products = [];
// Loop through each array value
var promises = [];
for (var slug in data.data){
var product = data.data[slug];
promises.push($http.get('content/products/' + product + '.json'));
}
$q.all(promises).then(function(response){
for (var i=0,len = response.length;i<len;++i){
products.push(response[i].data);
}
$scope.products = products;
}).catch(function(){
console.log('there was an error');
});
}).catch(function(){
console.log('there was an error');
});
我建议使用$q.all()
来保留http.get结果的顺序。另请注意,$scope.products
位于for循环之后,它将数据值分配给您指定的products
数组。