在 Angularjs 中的另一个 $http 中使用来自一个 $http 的响应

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

首先我想使用 $http 来接收一些数据(例如学生),然后我想再调用 $http 来获取例如学生详情。之后,我想将 studentDetails 的某些部分附加到学生 JSON。 我还需要第一次调用的响应,以便为第二次调用创建 url。

问题是我无法访问另一个内部的第一个 http 调用的响应。 有谁知道如何做到这一点?

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
           })
     }
  })

您正在使用延迟的反模式以及已弃用的 success/error-callbacks。您应该改为使用 then,因为它 returns 是一个承诺,并且您可以链接承诺。

以下是您如何操作的示例:

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);

我决定根据其名称以不同方式构造 appendStudentDetails 函数,但您可以像以前一样轻松地在方法中调用 getStudents()

注意不要在内部 then 函数中使用 i 变量,因为那样会导致闭包问题。

编辑:修复示例以避免 i 处于关闭状态。