当我循环遍历 Angularjs 的 $http post 服务时
for (var i = 0; i < $scope.tagStyles.length; i++) {
$scope.profilTag.tag = $scope.tagStyles[i].id_tag;
$scope.profilTag.texte = $scope.tagStyles[i].style ;
$scope.profilTag.profil = lastDocId;
$http.post('/ajouterProfilTag',$scope.profilTag)
.success(function(data){
if (data=='err'){
console.log("oops");
}
});
};
我只得到数据库中的最后一个元素。它与异步调用有关吗?
最佳答案
$http 文档:
直到下一个 $digest() 被执行,$http 服务才会真正发送请求。
可能发生的情况是 $scope.profilTag 通过引用 $http 传递并且仅在 $digest 之后发送。您在每次迭代时都覆盖了该引用,这就是为什么您只留下了最后一项。
请注意,函数有作用域,但 for 循环没有!
试试这个:
$scope.tagStyles.forEach(function(item){
var profilTag = {
tag: item.id_tag,
texte: item.style,
profil: lastDocId,
};
$http.post('/ajouterProfilTag',profilTag)
.success(function(data) {
if (data=='err'){
console.log("oops");
}
});
});
关于javascript - Angularjs 循环通过 $http.post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21020360/