0

I need to make two http.post() calls from angular controller and the result of the first one is to be used in the next call. The next call should not be made until and unless we receive the result of previous one. This whole logic needs to be repeated over a loop.

Logic---> for 1 to 5 function1-->http.post(object1) returns a deferred promise with data e.g. id1 Use the id1 as parameter for next call object2.id=id1 function2--->http.post(object2) returns some data.

Shubh
  • 19
  • 6

1 Answers1

0

Chaining your calls is the way to go. Once httpCall1 is resolved it will call httpCall2 with the response from the first.

$scope.amountOfCallsToMake = 5;
$scope.results = [];

$scope.makeCalls = function(){
  for(callIndex = 0; callIndex < $scope.amountOfCallsToMake; callIndex++){
    $scope.httpCall1().then(function success(response){
      return $scope.httpCall2(response.data);
    }).then(function success(response){
      $scope.results.push(response.data);
    }
  }
}

$scope.httpCall1 = function(){
  return $http({
    method: 'POST',
    url: //Somewhere
  )};
}

$scope.httpCall2 = function(callResponse){
  return $http({
    method: 'POST',
    url: //Somewhere else,
    data: {
      parameter: callResponse
    }
  )};
}
Patrick
  • 302
  • 2
  • 19