Chaining multiple $http.get() ng-init angularjs

971 Views Asked by At

Im working on a scenario where on page load i have 2 $http.get() request. One $http.get() are independent on another $http.get(). Every thing works fine.But in some situation my 2nd $http.get() request executes before the 1st $http.get() and i'm not able to get the desired output. How can we chain the request? Since i'm new to AngularJS i don't have that much idea.

$scope.onload = function()
{
    var responsePromise1 = $http.get(1st rest call);
    responsePromise1.success(function(data) { 

        console.log(data.platform.record);
        $scope.records=data.platform.record;
    });

    responsePromise1.error(function(data, status, headers, config) {
        alert("ajax failed");
    });

    var responsePromise2 = $http.get(2nd rest call);
    responsePromise2.success(function(data2) {
        console.log(data2.platform.record);
        $scope.records2=data2.platform.record;
    });

    responsePromise2.error(function(data2, status, headers, config) {
        alert("ajax failed");
    });
}
$scope.butto = function(datafrom1st,datafrom2nd)
{
    var responsePromise3 = $http.get(3rd rest call);
    responsePromise3.success(function(data3) { 
        console.log(data3.platform.record);
        $scope.records3=data3.platform.record;
    });

    responsePromise1.error(function(data3, status, headers, config) {
        alert("ajax failed");
    });
}
<body>
  <div ng-init="onload()">
    <div ng-repeat="record in records">
      {{record.id}}
    </div>
    <div ng-repeat="record2 in records2">
      {{record2.name}}
    </div>
    <button type="button" class="btn btn-primary btn-sm ng-cloak"
            style="padding-bottom:25px;font-weight:bold;" 
            ng-init="butto(record.id,record2.name)">
      {{record3.data}}
    </button>
  </div>
</body>
5

There are 5 best solutions below

0
On

Try doing this

   $scope.onload = function()
    {
    var responsePromise1 = $http.get(1st rest call);
        responsePromise1.success(function(data) { 
    SecondInit()
        console.log(data.platform.record);
            $scope.records=data.platform.record;
        });

        responsePromise1.error(function(data, status, headers, config) {
            alert("ajax failed");
        });


      }
    function SecondInit(){
    var responsePromise2 = $http.get(2nd rest call);
        responsePromise2.success(function(data2) {
            console.log(data2.platform.record);
            $scope.records2=data2.platform.record;
        });

        responsePromise2.error(function(data2, status, headers, config) {
            alert("ajax failed");
        });

Here i am trying to bind the second api call to function named SecondInit() and invoke in it on success of first api call this might help

0
On

You can achieve this, using $q.all as per Hoyen's suggestion:

$scope.onload = function(){

    var promise1 = $http.get('/request1');
    var promise2 = $http.get('/request2');

    $q.all([ promise1, promise2 ]).then(function(data){
        var response1 = data[0].platform.record;
        var response2 = data[1].platform.record;

        $scope.records = response1.map(function(e, i){
            var id = e.id;
            var name = response2[i].name;
            return {id: id, name: name};
        });
    });
};

Then in your view, do this:

<body>
    <div ng-init="onload()">
        <div ng-repeat="record in records">
            <div>{{record.id}}</div>
            <div>{{record.name}}</div>
            <button type="button" class="btn btn-primary btn-sm ng-cloak" style="padding-bottom:25px;font-weight:bold;" 
                ng-click="butto(record.id,record.name)"></button>
        </div>
    </div>
</body>

This should work, but I would really recommend you find a good up-to-date angular tutorial and read up on best practices. This isn't really the optimal way to solve this kind of problem.

6
On

Call 2nd request inside success method of 1st request:

var responsePromise1 = $http.get(1st rest call);
        responsePromise1.success(function(data)
        { 
          console.log(data.platform.record);
          $scope.records=data.platform.record;
var responsePromise2 = $http.get(2nd rest call);
        responsePromise2.success(function(data2)
        {
        console.log(data2.platform.record);
        $scope.records2=data2.platform.record;
        });
        responsePromise2.error(function(data2, status, headers, config)
        {
          alert("ajax 2 failed");
        });
        });
        responsePromise1.error(function(data, status, headers, config)
        {alert("ajax failed");
        });
0
On

The $http API is based on the deferred/promise APIs exposed by the $q service.

$http
  .get(1st rest call)
  .then(function(data){
       $scope.records = data.platform.record;
       return $http.get(2nd rest call);
  })
  .then(function(result){
     //result of 2nd rest call
  })
  .catch(function(err){
     // Here catch error
  })
8
On

You can try using Promise.all, if they are independent of each other. But you need to execute the code in a specific order.

var responsePromise1 = $http.get(1st rest call);
var responsePromise2 = $http.get(2nd rest call);
var promises = [responsePromise1,responsePromise2]

// Array of Promises
$q.all(promises)
    .then(function(data){
         var data1 = data[0];
         var data2 = data[1];
         // Put logic here to handle both responses.
         return $http.get(3rd rest call);
     })
     .then(function(data3){
         // Put logic here to handle third response
     });