Akram Akram - 2 months ago 7
AngularJS Question

Use loop in http post AngularJS asynchronous




I want to use foreach to get item by item and pass it to http post.

For example i want to get all chapters in lesson, i get this

[”angularjs","react","ionic"]
, and i want to pass angularjs to get all chapters in
lessons of angualrjs .


Here is my code .

// asynchronous http
$scope.allLessons = [];
var init = function () {
var x = JSON.parse($localStorage.currentUser);
$http({
method: 'POST',
url: 'http://localhost/hrm/public/checkLs',
data: {email: x.email}
}).success(function (data) {
$scope.isRole.push(data);
console.log($scope.allLessons);
$scope.isRole.forEach(rr){
$http({
method: 'POST',
url: 'http://localhost/hrm/public/hpers',

data: {
name: rr
},
}).success(function (data) {
console.log(data);
}).error(function (data) {
console.log(data);
});
};

}).error(function (data) {
console.log(data);
});
};
init();


So in first http i get array of lessons
[”angularjs","react"....]
. and in second i get an error.


My backend get just name of lesson string not array, so how can i pass lesson by lesson for get the chapters of the lesson that i want ?


How and why is the best why to do it asynchronous ? and thanks.

Answer

For doing it synchronously , you can do something like below.

//post requests 
    var Requests = [
      {
      url:"your url1",
      data:"your data"
      },
      {
      url:"your url2",
      data:"your data"
      },
      ];

  if (Requests.length>0) {
     var exit = false;
     var len = Requests.length-1;
     executePost(0, Requests, len);
  }

     var executePost = function (i, Requests, len)
        {
          if (Requests[i]!=undefined && (i<=len)) 
           {
             var request = Requests[i];
             var url = request.url;
             var data = request.data;
             $http.post(url, data, { headers: { "contentType": "application/json; charset=utf-8" } })
             .then(function (success) 
               {
                 console.log("Processed  " + (i + 1));              //processed log
//you can store the data to any variable here

                   if ((i + 1) <= len) {
                       executePost(i + 1, Requests, len);
                   }
               },
              function (error) 
               {
                console.log("Unsuccessfull  " + (i + 1)); 
              });
          }
       }

Here the function executePost having three parameters is called recursively.

Comments