Angularjs循环$ http.post

bad*_*oum 2 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('/ajouterProfilTag',$scope.profilTag) 
  .success(function(data){ 
    if (data=='err'){ 
      console.log("oops"); 
    }     
  });
};
Run Code Online (Sandbox Code Playgroud)

我只得到数据库中的最后一个元素.它是否与异步调用有关?

Ila*_*mer 9

$ http docs:

The $http service will not actually send the request until the next $digest() is executed.

可能发生的是$ scope.profilTag通过引用传递给$ http并且仅在$ digest之后发送.您可以在每次迭代时覆盖该引用,这就是您只留下最后一项的原因.

请注意,函数具有范围,但循环不具有!

试试这个:

$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"); 
    }
  });

});
Run Code Online (Sandbox Code Playgroud)


And*_*iov 7

您可能想要使用AngularJs promise API.

var promiseArray = [];

for (/*your loop statements*/) {
 promiseArray.push($http.post('/url', $scope.var));
}

$q.all(promiseArray).then(function(dataArray) {
    // Each element of dataArray corresponds to each result of http request.
});
Run Code Online (Sandbox Code Playgroud)

请参阅$ http服务文档中的 Usage-> returns部分,以了解通过dataArray参数返回的内容.