Javascript Angularjs循环trought$http.post

Javascript Angularjs循环trought$http.post,javascript,angularjs,Javascript,Angularjs,当我遍历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('/ajou

当我遍历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"); 
    }     
  });
};
for(变量i=0;i<$scope.tagStyles.length;i++){
$scope.profilTag.tag=$scope.tagStyles[i].id\u标记;
$scope.profilTag.texte=$scope.tagStyles[i].style;
$scope.profilTag.profil=lastDocId;
$http.post('/ajuterprofiltag',$scope.profilTag)
.success(函数(数据){
如果(数据=='err'){
console.log(“oops”);
}     
});
};

我只得到数据库中的最后一个元素。它与异步调用有关吗

您可能需要使用AngularJs


请参阅中的用法->返回部分,以了解通过dataArray参数返回的内容。

这是因为请求以异步方式发出。真正的请求在所有迭代完成后发送。尝试发送如下参数的副本

$http.post('/ajouterProfilTag',angular.copy($scope.profilTag)) 
$http文档:
在执行下一个$digest()之前,$http服务不会实际发送请求。

可能发生的情况是,$scope.profilTag通过引用传递到$http,并且仅在$digest之后发送。每次迭代都会覆盖该引用,这就是为什么只留下最后一项

请注意,函数有作用域,但for循环没有

请尝试以下方法:
你说的“循环”是什么意思?在代码中看不到任何循环。@AndreyShustariov我说的循环是指我在for loopWell中添加了$http.post,成功回调方法是异步的。它将在将来执行。甚至在你的loup完成之后。@AndreyShustariov我已经编辑了这篇文章,我需要做的是在循环中调用$http.post有什么想法吗?有没有办法让成功方法的回调同步?对我来说,Ilan的回答更有效,因为它将所有请求保存在一个数组中,并在没有任何中断的情况下一个接一个地发送它们。Ilan的回答让其他请求在两者之间发送,这对我的案例来说是不可取的。这是解决我问题的最好办法,因为无论我做什么,我都让scope发送同一个对象。我觉得我在作弊,因为这样做完美且容易,而我不必忍受关闭的三级折磨。
$http.post('/ajouterProfilTag',angular.copy($scope.profilTag)) 
$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"); 
    }
  });

});