sabbir sabbir - 3 months ago 9
AngularJS Question

javascript: http call inside nested for loop

In my angular app, I have two array as like as given below:

$scope.data = ["val 10,val 11,val 12", "val 20,val 21,val 22", "val 30,val 31,val 32"];

$scope.fields = [ "key1", "key2", "key3" ];


And now I need to send each data of array (
$scope.data
) to server with the following format:

{
key1: 'val 10',
key2: 'val 11',
key2: 'val 12',
}
{
key1: 'val 20',
key2: 'val 21',
key2: 'val 22',
}
{
key1: 'val 30',
key2: 'val 31',
key2: 'val 32',
}


But problem is: when I send data to server, I only get the last value of
$scope.data
. My code is given below:

// $scope.data = ["val 10,val 11,val 12", "val 20,val 21,val 22", "val 30,val 31,val 32"];
_.each($scope.data, function(result, index) {

var dataArray = result.split(","); // ["val 10" ,"val 11", "val 12"]
// ["val 20" ,"val 21", "val 22"]
// ["val 30" ,"val 31", "val 32"]

_.each(dataArray, function(info, position) {

if( info !== null || info !== '' || info.length > 0 ) {
$scope.data[ $scope.fields[position] ] = info; // { key1: 'val 10', key2: 'val 11', key2: 'val 12' }
// { key1: 'val 20', key2: 'val 21', key2: 'val 22' }
// { key1: 'val 30', key2: 'val 31', key2: 'val 32' }
}
});

$http
.post(url + '/import-data', {
"data": $scope.data
})
.then(function (res) {
console.log(res); // in server I always get the following object
// { key1: 'val 30', key2: 'val 31', key2: 'val 32' }
// { key1: 'val 30', key2: 'val 31', key2: 'val 32' }
// { key1: 'val 30', key2: 'val 31', key2: 'val 32' }
}, function (error) {
console.log("error : ", error);
})

});


How can I solve this problem? Thanks in Advance...

Answer

try this:

_.each($scope.data, function(result, index) {

    var dataArray = result.split(","); 

    $http
       .post(url + '/import-data', {
            "data": _.object( $scope.fields, dataArray)
       })
      .then(function (res) {
          console.log(res); 
       }, function (error) {
          console.log("error : ", error);
       })

  });
Comments