【问题标题】:Use response from one $http in another $http in Angularjs在 Angularjs 中使用另一个 $http 中的一个 $http 的响应
【发布时间】:2017-07-25 13:51:14
【问题描述】:

首先我想使用 $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
           })
     }
  })

【问题讨论】:

  • 您可以简单地将较早的 http 调用响应存储在您的作用域变量中,并在下一次调用的成功回调中使用它。
  • 应该是:var studentsWithDetails = response.data;
  • 响应中存在什么?
  • @Vivz 内部响应我有 20 名学生组成的数组,其中包含一些信息,但是从第二个 http 调用中,我得到了一些其他信息,我想将这些信息附加到数组的每个元素中
  • 你确定studentsWithDetails是一个数组吗?你能安慰检查一下吗

标签: angularjs json http promise angular-promise


【解决方案1】:

您正在使用延迟的反模式以及已弃用的成功/错误回调。你应该改用then,因为它返回一个promise,你可以链接promise。

下面是一个例子:

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 被关闭的问题。

【讨论】:

  • 谢谢!!我在访问.then 中的studentWithDetails[i] 时仍然存在问题。它是未定义的。你知道为什么会这样吗?
  • 我已经修复了上面的例子,以避免在内部then-callback 中使用i。原因是变量i 在闭包下被引用,所以当回调被调用时,循环将会结束并且i 将是每次调用回调的错误值。这可能会解决您的问题。
  • 非常感谢!现在可以了!这是一个非常好的解决方案! :)
  • 很棒的伙伴。很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 2018-01-28
  • 2022-01-18
相关资源
最近更新 更多