AngularJS: forEach http get data -等待其他方法,直到所有来自循环的数据被加载
AngularJS: forEach http get data - wait for other method untill all data from loop is loaded
我的代码是:
var commentAuthorIds = [];
$scope.commentAuthors = [];
angular.forEach($scope.news.Comments, function(el) {
if (angular.isDefined(el.AuthorId)){
commentAuthorIds.push(el.AuthorId);
}
});
commentAuthorIds = $filter('unique')(commentAuthorIds);
var promises = [];
angular.forEach(commentAuthorIds, function(el) {
promises.push($scope.getCommentsAuthorData(el));
});
$q.all(promises).then(function(){
console.log('all data loaded!');
angular.forEach($scope.news.Comments, function(el) {
angular.forEach($scope.commentAuthors, function(subEl) {
if (el.AuthorId === subEl.Id){
el.Author = response.FirstName + ' ' + response.LastName;
el.Thumbnail = response.Thumbnail;
}
});
});
});
$scope.getCommentsAuthorData = function(userId){
$http.get('/app/' + $scope.company.Id + '/users/' + userId, {
headers: {
'Content-Type': 'application/json'
}
})
.success(function(response) {
$scope.commentAuthors.push(response);
});
};
和i需要在$q.all(promises).then(function(){...
加载后才调用angular.forEach($scope.news.Comments, function(el) {...
我做错了什么?我的代码不工作(
getCommentsAuthorData不返回承诺…在$http
前添加返回$scope.getCommentsAuthorData = function(userId){
return $http.get('/app/' + $scope.company.Id + '/users/' + userId, {
headers: {
'Content-Type': 'application/json'
}
});
};
基于此:
all函数返回一个值数组的promise。当这个类的实现值原来的承诺,按原来的顺序排列。如果其中一个如果承诺被拒绝,则立即返回承诺已拒绝,未等待批处理的剩余部分。
在您的情况下这可能是一个问题....所以使用$q扩展名可以解决这个问题,将它添加到您的应用程序中然后你可以这样做:
$q.allSettled(promises).then(function(responses){
angular.forEach(responses,function(response){
if(response.status!="rejected"){
$scope.commentAuthors.push(reponse.value);
}else{
console.log(response.reason);
}
});
});
相关文章:
- 对于加载时间过长的循环来说是巨大的
- 将所选类别循环到ul>李用加载更多按钮
- 文本淡入淡出后循环加载页面
- FileReader加载端中循环变量的值
- 无法从 .each 循环加载谷歌地图上的两个标记
- 在window.print()中加载为循环指令而编译时准备DOM失败
- 如何在背景图像的循环数组中预加载图像
- mysql循环-预加载数据
- 随机页面加载后循环播放其余视频
- Javascript:用循环在谷歌地图上加载标记
- Jquery选项卡:打破创建-选择-重新加载循环
- 替换从外部 IN for 循环加载的 HTML 字符串中的字符
- CasperJS循环加载下一页
- imacro 每 10 次循环加载一次 URL
- 循环加载javascript函数
- 使用for循环加载RSS提要的Javascript
- 使用for循环加载Jssor滑块
- 图像循环加载不到位
- 通过JavaScript循环加载的项没有按正确的顺序显示
- 如何在Imacros中为条件循环加载javascript变量中的csv Col值