0

Im working with angularjs $http.get() request .On load of the page im doing two rest api call.The api is executing correctly.I have a button which use the data from the two rest api calls.I'm facing a issue that is my function get executed before the $http.get() response and i'm not able to get the desired result.How can i make my function to execute after the response from the two $http.get() request. Can anyone help.i'm stuck at this point

 var responsePromise5 = $http.get("1st rest call");                   
   responsePromise5.success(function(data1) {
         $scope.id = data1.platform.user.id;
      var responsePromise = $http.get("2nd rest call");            
            responsePromise.success(function(data2) 
             {
             console.log(data2.platform.record);
             $scope.records= data2.platform.record;      
             });
             responsePromise.error(function(data2, status, headers, config) {
             alert("AJAX failed!");
             });   
           });
            responsePromise5.error(function(data1, status, headers, config) {
             alert("AJAX failed!");
        }); 
$scope.hello = function(a,b)
{
  //here i want to call another rest api
  }
<div ng-repeat="record in records">
  {{record.name}}
  <button ng-init=hello(record.unin,id)>abc</button>
</div>  
dockerrrr
  • 277
  • 1
  • 5
  • 17
  • Call the $scope.hello function after the success of the $http.get – Hmahwish Dec 26 '16 at 07:55
  • See [AngularJS $q Service API Reference - Chaining Promises](https://docs.angularjs.org/api/ng/service/$q#chaining-promises). Also see [SO: Why are angular $http success/error methods deprecated? Removed from v1.6?](http://stackoverflow.com/a/35331339/5535245). – georgeawg Dec 26 '16 at 08:46

2 Answers2

0

You can use $q.all() -

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

More details here - https://docs.angularjs.org/api/ng/service/$q

Developer
  • 6,240
  • 3
  • 18
  • 24
  • can you explain how can i use $q.all() in the above scenario .Im stuck – dockerrrr Dec 26 '16 at 07:59
  • If I understood your question correctly, you have some function to be executed only after successful completion of 2 ajax calls. Thats where `$q.all()` is useful. You can get sample implementation here - https://www.martin-brennan.com/using-q-all-to-resolve-multiple-promises/ – Developer Dec 26 '16 at 08:02
0

Call whatever code you want to call after you get the response of your http request inside then like below

$http.get('first http request').then(function(res){
  $http.get('second http request').then(function(res2){
     // your code
    })
  })
Rishi Tiwari
  • 1,041
  • 1
  • 10
  • 20