0

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?

2 Answers 2

1

Convert this

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

to this

$http.get('api/url/names/'+res.data[0].id)
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry that was a typo in the question, your response is how I have it in my code.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.