0

I had controller and function getData as shown. The problem is that the $scope.results outside the for loop has no content. While inside the second http.get request, It has content.

appControllers.controller('MyaSellerOrderCtrl', ['$scope', '$rootScope', 'Order', '$http',
    function($scope, $rootScope, Order, $http) {
        $scope.results = [];
        $scope.getData = function() {
               $http.get('api/orders/business/?user_id=' + $rootScope.user.user_id).success(function(data){
                    for (var i = 0; i < data.length; i++) {
                        $http.get('api/orders/seller/?business_id=' + data[i].business_id).success(function(data1){
                             // console.log(data1);        
                             $scope.results[i] = data1;
                       });
                     }
                     console.log($scope.results);
                });
         };
         $scope.getData();
     }]);
Riyas TK
  • 1,231
  • 6
  • 18
  • 32

1 Answers1

1

Explanation

// STEP 1: your first request
 $http.get('api/orders/business/?user_id=' + $rootScope.user.user_id).success(function(data){
    // STEP 2 : your loop started
    for (var i = 0; i < data.length; i++) {
         // STEP 3 : you hit another request. it does not block any operation because it run asynchronously.
         // it also does not wait for any previous request to be completed.
        $http.get('api/orders/seller/?business_id=' + data[i].business_id).success(function(data1){
             // console.log(data1);
             $scope.results[i] = data1;
       });
     }
     // STEP 4: this doesn't wait for STEP 3 to complete because it [STEP 3 ] run asynchronously.
     // this lin run after for loop complete.
     console.log($scope.results); // so you get nothing here as STEP 3 is still running
});

Reference

  1. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
  2. How to $http Synchronous call with AngularJS
Community
  • 1
  • 1
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40