javascript - Angularjs 循环通过 $http.post

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

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

最佳答案

$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/

相关文章:

javascript - 防止 Javascript 中对象的扩展

javascript - 如果键值匹配,则合并并减少。重构 JSON 数据响应

angularjs - $modalInstance 对话框关闭,但屏幕仍呈灰色且无法访问

javascript - 取消或停止递归 promise 链中的 $timeout

node.js - Angularjs $http 似乎不理解响应中的 "Set-Cookie"

javascript - 删除 ng-click 上的 Angular 限制

javascript - 通过 AJAX 将数组发送到 PHP

javascript - 使用提示时反转数组

javascript - Threejs 从场景中删除所有对象

java - Spring Security不通过Spring Session EnableRedisHttpSession重用身份验证数据