Benjamin Franck
Benjamin Franck

Reputation: 1

AngularJS $http.get within a $http.get

I make a get call and retrieve some data that I want to use to make another get call and place that data within the $scope. Something like this.

$http.get('api/url/items').then(function(res){
  $scope.items = res.data;
  $http.get('api/url/names/' + res.data[0].id).then(function(res){
    console.log(res.data.name);
    $scope.name = res.data.name;
  }
}

The $scope.items is being populated but the $scope.name is not. The console.log gives the correct data but seemingly after the view as been rendered. How can I get the second $http.get to populate the within the $scope before rendering the view?

Upvotes: 0

Views: 389

Answers (2)

Benjamin Franck
Benjamin Franck

Reputation: 1

I had two problems in my original code that was not in my simplified question that I now solved.

  1. I was using a function to call the second $http.get. By the time that function callback came the original $http.get had already resolved so I moved that function code within the first $http.get.
  2. I was using a for loop (var i) to both call the second $http.get function and set the value within my $scope.items[i]. By the time the $http.get resolved that i var already reached it's limit causing an undefined error. I created a counter var to change only within the second $http.get so the indexes match correctly.

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Convert this

$http.get('api/url/names/res.data[0].id')

to this

$http.get('api/url/names/'+res.data[0].id)

Upvotes: 1

Related Questions