VitezKoja
VitezKoja

Reputation: 173

Use response from one $http in another $http in Angularjs

First of all I want to use $http in order to receive some data (e.g. students), then I want to make another $http call to get e.g. studentDetails. After that I want to append some part of studentDetails to students JSON. Also I need response from the first call in order to create the url for the second call.

Problem is that I cannot access response of the first http call inside the another. Does anybody know how this can be done?

var getStudents = function(){
   var deferred = $q.defer();
   $http.get("https://some_url")
   .success(function(response){
      deferred.resolve(response);
   }).error(function(errMsg){
      deferred.reject(errMsg);
   });
   return deferred.promise;
}
var appendStudentDetails = function(){
  getStudents().then(function(response){
     var studentsWithDetails = response;
     for(var i=0; i<studentsWithDetails.length; i++){
        $http.get("some_url/"+studentWithDetails[i].user.details+"/")
           .success(function(res){

             //here I want to append the details, 
             //received from the second http call, to each student 
             //of the array received from the first http call 

             //PROBLEM: I cannot access response of the
             //first http call inside the another
           })
     }
  })

Upvotes: 2

Views: 54

Answers (1)

Nikolaj Dam Larsen
Nikolaj Dam Larsen

Reputation: 5674

You're using the deferred anti-pattern as well as the deprecated success/error-callbacks. You should instead use then, since it returns a promise, and you can chain promises.

Here's an example of how you could do it:

function getStudents(){
    return $http.get('[someurl]');
}
function appendStudentDetails(studentsWithDetails){
    for(var i=0; i<studentsWithDetails.length; i++){
        appendSingleStudentDetails(studentsWithDetails[i]);
    }
}
function appendSingleStudentDetails(singleStudent){
    $http.get("some_url/"+singleStudent.user.details+"/")
        .then(function(res){
            // Append some stuff
            singleStudent.stuff = res.data;
        });
}

// Call it like this:
getStudents()
    .then(function(response){ return response.data; })
    .then(appendStudentDetails);

I decided to structure the appendStudentDetails function a little differently, based on its name, but you could as easily just call getStudents() within the method as you did before.

Beware not to use the i-variable inside your inner then-function, as that would cause you troubles with closure.

Edit: Fixed example to avoid problem with i being under closure.

Upvotes: 3

Related Questions