Angularjs - Multiple $http REST calls (second call dependent on output of first)

Leapahead

I am a newbie to AngularJs world - I am trying to get data from two REST WS calls.

First one returns a set of data (works fine)- using the value of data from frist one I need to make another webservice call and retrive the data and print in a table.

Below is what I have tried so far: HTML:

<table ng-table="tableParams" id="request_table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
    <tr>
        <th>Number</th>
        <th>Price</th>
        <th>Short Description</th>
        <th>Requested for</th>
        <th>State</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="request in req_list | orderBy:sortType:sortReverse | filter: searchItem">
        <p ng-repeat="item in fetchRequest(request.price)"></p>

        <td>{{request.number }}</td>
        <td>{{request.price}}</td>
        <td>{{request.short_description}}</td>
        <td>{{request.requested_for.display_value}}</td>
        <td>{{request.stage}}</td>
    </tr>

</tbody>

Script:

            angular.module('sc_request_list')
            .controller('MyRequestItems', [
                '$scope',
                '$http',
                function($scope, $http) {
                    $scope.sortType = 'number' //set the default sort type
                    $scope.sortReverse = false; // set the default sort order
                    $scope.searchItem // set the default search/filter term
                    $scope.itemUrl = '/api/sc_request';
                    $scope.reqUrl = '/api/sc_req_item';
                    $http.defaults.headers.common.Accept = "application/json";
                    $scope.fetchRequestItemList = function() {
                        $http({
                            method: 'GET',
                            url: $scope.itemUrl,
                        }).


                        success(function(data, status) {
                            var result = data;
                            var json = JSON.stringify(result);
                            var data = JSON.parse(json);
                            $scope.req_list = data.result; // response data 

                        }).
                        error(function(data, status) {
                            $scope.req_list = [{
                                "req_list": "Error fetching list"
                            }];
                        });

                    }

                    $scope.fetchRequest = function(request) {
                        console.log("Request Number is: " + request);
                        $http({
                            method: 'GET',
                            url: $scope.reqUrl + "/" + request,
                        }).


                        success(function(data, status) {
                            var result = data;
                            var json = JSON.stringify(result);
                            var data = JSON.parse(json);
                            $scope.req = data.result; // response data 

                        }).
                        error(function(data, status) {
                            $scope.req = [{
                                "req": "Error fetching list"
                            }];
                        });

                    }
                }


            ]);

Any help much appreaciated.

tombarti

Your calls are made asynchronously so while the calls are being made, the rest of the code is still executing. Thus,

<p ng-repeat="item in fetchRequest(request.price)"></p>

is executed before request.price is even defined.

What you need to do is chain the calls to your api calls:

$http({
  method: 'GET',
  url: $scope.itemUrl,
}).


success(function(data, status) {
  var result = data;
  var json = JSON.stringify(result);
  var data = JSON.parse(json);
  $scope.req_list = data.result; // response data 
  
  //Loop through requests
  $scope.req_list.foreach(function (elem, index) {
    //chained call is here
    $scope.fetchRequest(elem.price, index);
  });
}).

error(function(data, status) {
  $scope.req_list = [{
    "req_list": "Error fetching list"
  }];
});

$scope.fetchRequest = function(request, index) {
  console.log("Request Number is: " + request);
  $http({
    method: 'GET',
    url: $scope.reqUrl + "/" + request,
  }).

  success(function(data, status) {
    var result = data;
    var json = JSON.stringify(result);
    var data = JSON.parse(json);
    //Attach result of api call to apropriate element of req_list array
    $scope.req_list[index].items = data;

  }).
  error(function(data, status) {
    $scope.req = [{
      "req": "Error fetching list"
    }];
  });

}
}

And then change:

<p ng-repeat="item in fetchRequest(request.price)"></p>

To:

<p ng-repeat="item in request.items"></p>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Multiple $http calls in AngularJS

AngularJs : Multiple Calls for $http service

How to call multiple dependent api calls with time intervals using RxJS

Angular2 - Multiple dependent sequential http api calls

setting HTTP Header for angularjs REST calls

Execute a second http call only if first fails

make multiple http calls synchronously in AngularJs

Sub calls First Sub but does not call second sub

AngularJS $http REST call returns null data

Multiple AddParameter calls only add the first parameter, ignoring the rest

How to merge multiple API calls into one call in REST API

Swift 4 UITableViewCell first tap doesn't call segue, and second tap calls segue with the first cell data

AngularJS directive calls multiple time rather than to call a single time

AngularJS REST service calls

How to call multiple dependent functions?

Executing async tasks when second dependent on first

Abort AngularJS $http request, deeply nested in multiple service calls

Angularjs - Combining data from multiple $http calls in a for loop

First and Second Call in C

AngularJs directive and $http calls

Angular/RXJS nested observables using the response from the first call in the second two calls

Is it safe to assume that if I make two calls to async_read, the second call will be processed only after the first is processed?

Ajax.BeginForm works first time, but calls method twice from second call

Preventing Multiple http calls

Making a call with RX and then making multiple parallel calls from the result of the first call

Creating a Redux Observable Epic with multiple API Calls - Passing the results of the first into the second

rest urls calls parallely angularjs

How to mock method to return value X at first call, and Y on rest calls?

First django rest api call returns request.user as AnonymousUser but further calls return proper user