Angularjs loop trought $http.post

前端 未结 3 637
死守一世寂寞
死守一世寂寞 2021-01-06 23:51

When I loop through the $http post service for Angularjs

for (var i = 0; i < $scope.tagStyles.length; i++) {
  $scope.profilTag.tag = $scope.tagStyles[i].         


        
相关标签:
3条回答
  • 2021-01-07 00:14

    $http docs:

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

    What probably happens is that $scope.profilTag is being passed by reference to $http and only being sent after a $digest. You override that reference each iteration and that's why you only left with your last item.

    Be aware that functions has scopes but for loops don't!

    Try this instead:

    $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"); 
        }
      });
    
    });
    
    0 讨论(0)
  • 2021-01-07 00:16

    You may want to use 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.
    });
    

    See Usage->returns section in $http service docs, to understand what is returned via dataArray parameter.

    0 讨论(0)
  • 2021-01-07 00:22

    It is happened because request makes asynchronously. Real requests are sending after all iterations have completeted. Try send copy of params like this

    $http.post('/ajouterProfilTag',angular.copy($scope.profilTag)) 
    
    0 讨论(0)
提交回复
热议问题