【问题标题】:AngularJs http get response is undefined But the data is present inside success functionAngularJs http获取响应未定义但数据存在于成功函数中
【发布时间】:2015-10-29 19:29:26
【问题描述】:

我是 Angular 新手。我试图从 http get 方法获取 json 响应。

我的代码是,

app.factory('getdata', function ($http, $q){
  this.getlist = function(){       
    alert('1');
    return $http.get('http://www.w3schools.com/angular/customers.php',{'Access-Control-Allow-Origin': 'localhost:*'})
    .then(function(response) {
      console.log('response'); console.log(response.data); //I get the correct items, all seems ok here
        alert('2');
        return response.data;
      });            
  }
  return this;
});
/* Stream page controller */
app.controller('streamCtrl', function($scope,getdata, $ionicSlideBoxDelegate, $timeout, $ionicScrollDelegate, $location, $sce){
  $scope.trustSrc = function(src) {
    return $sce.trustAsResourceUrl(src);
  }
  getdata.getlist()
  .then(function(arrItems){
   $scope.sliders = arrItems;         
 });
alert($scope.sliders);

收到类似 1、“未定义”和 2 的警报 但 $scope.sliders 有数据。因为一旦我调整屏幕大小,它就可以工作,而且我可以在

中获得正确的警报
getdata.getlist().then(function(arrItems) {
  $scope.sliders = arrItems;         
  alert($scope.sliders);
});

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    得到警报的原因是undefined因为你没有在控制器中定义$scope.sliders并且http请求是异步的所以alert($scope.sliders);函数调用之前从data响应并将该数据设置为$scope.sliders

    只有在获得成功响应后才能获得alert($scope.sliders); 值。

    另一种可能性是您可以设置$scope.sliders = {},然后使用alert($scope.sliders);,当then 函数被调用时,{} 在警报中显示alert 显示实际响应。

    plunker基于issue

    检查 cmets 并在新 plunker 中更新代码

    【讨论】:

    • 仍然收到未定义的警报($scope.sliders)
    • @SarjanDesai 尽量不要更新别人的答案,至少要礼貌
    • @Alex Man 我正在尝试完成我之前不完整的答案
    • 你现在可以试试这个吗plnkr.co/edit/moOfwxFNM5ttH9wBzzvk?p=preview
    • 使用新添加的 plnkr 检查更新的答案并在 plnkr 中读取 cmets
    【解决方案2】:

    $http 是一个异步调用,所以发生的情况是您在 line number 6 触发了一个 http 调用,而它得到了 line number 10 的响应因为所有 http 角度调用都是异步的,所以被执行。

    这就是你收到undefined的原因

    如果您想在响应后做任何事情,只需执行 http 承诺中的内容,即。在.then 功能块内,如下所示

    getdata.getlist()
      .then(function(response){ // http promise block
         $scope.sliders = response.data;
         console.log($scope.sliders);
    });
    

    【讨论】:

    • 你能在这里试试吗plnkr.co/edit/moOfwxFNM5ttH9wBzzvk?p=preview 我仍然不确定
    • @AnandhakumarR 我见过你的 plunker,就像.then.success 是另一个 http 承诺,你把警报放在承诺之外,这就是你得到 undefined 的原因
    • @AnandhakumarR alert($scope.names) 将在 http 调用完成之前执行,这就是为什么建议将所有内容都放在 promise 块中的原因,即。 .success.then 功能块
    猜你喜欢
    • 2015-04-02
    • 1970-01-01
    • 2023-01-11
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2020-01-16
    • 1970-01-01
    相关资源
    最近更新 更多