$ http.get中的AngularJS $ http.get

时间:2016-02-19 17:41:34

标签: angularjs angular-http

我进行了一次调用并检索了一些我想用来进行另一次调用的数据,并将这些数据放在$scope中。这样的事情。

$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;
  }
}

正在填充$scope.items,但$scope.name未填充。 console.log提供了正确的数据,但看起来像是在渲染后的视图。在呈现视图之前,如何让第二个$http.get填充$scope内的内容?

2 个答案:

答案 0 :(得分:1)

转换此

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

到这个

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

答案 1 :(得分:0)

我的原始代码中有两个问题,而不是我现在解决的简化问题。

  1. 我正在使用一个函数来调用第二个$ http.get。当函数回调出现时,原始的$ http.get已经解决,所以我在第一个$ http.get中移动了该函数代码。
  2. 我使用for循环(var i)来调用第二个$ http.get函数并在$ scope.items [i]中设置值。当$ http.get解析i var已达到它的限制时导致未定义的错误。我创建了一个仅在第二个$ http.get内更改的计数器var,以便索引正确匹配。
相关问题