Himanshu Bhuyan
Himanshu Bhuyan

Reputation: 306

Angular js api url in loop

$http({method: 'GET', url: '/xxx/xxx/xas'}).success(function(data) {        
    $scope.website = data.websites;
    });

$http({method: 'GET',url: '/xx/xasxxx?websiteId='+$scope.website.websiteId}).success(function(data) {
     $scope.onlinedata1 = data.coupons;                      
 });

I try to get websiteID from top url and pass that id in to 2nd url .my json data structure

"websites":[{
     "websiteName":"Flipkart",
     "websiteId":"1",
      },
      {
     "websiteName":"asas",
     "websiteId":"5",
      }]

Try to pass every id one by one. I am using AngularJS v1.2.17.

Upvotes: 1

Views: 252

Answers (2)

Sajev Lucksman
Sajev Lucksman

Reputation: 31

Use $q - service in module ng A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

Upvotes: 0

cafonso
cafonso

Reputation: 909

Move the second HTTP call within the success callback of the first one:

$http({method: 'GET', url: '/xxx/xxx/xas'}).success(function(data) {        
    $scope.website = data.websites;

    for (var i = 0; i < data.websites.length; i++)
    {
        $http({method: 'GET',url: '/xx/xasxxx?websiteId='+data.websites[i].websiteId}).success(function(data) {
            $scope.onlinedata1 = data.coupons;                      
        });
    }
});

This can be simplified considering that your requests are GETs:

$http.get('/xxx/xxx/xas')
    .then(function(res) {        
        for (var i = 0; i < res.data.websites.length; i++)
        {
            $http.get('/xx/xasxxx?websiteId='+res.data.websites[i].websiteId)
                .then(function(res) {
                    $scope.onlinedata1 = res.data.coupons;                      
            });
        }
});

Please note that the above will issue one request for each website returned by the API. If you have control over the API you might want to consider accepting multiple website IDs on the second URL resource (/xx/xasxxx?websiteIds=1,5,7,12,56) so as to limit the number of requests issued by the client.

Upvotes: 1

Related Questions