AngularJs http get响应未定义但数据存在于success函数内 [英] AngularJs http get response is undefined But the data is present inside success function

查看:159
本文介绍了AngularJs http get响应未定义但数据存在于success函数内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新角色。我试图从http get方法获取json响应。

Am new to angular. I have tried to get the json response from http get method.

我的代码是,

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,'undefined'和2
但是$ scope.sliders有数据。因为一旦我调整屏幕大小并且我可以得到正确的警报在

am getting the alert like 1, 'undefined' and 2 but the $scope.sliders has the data. because It was working once I resize the screen and also I can get correct alert inside the

getdata.getlist().then(function(arrItems) {
  $scope.sliders = arrItems;         
  alert($scope.sliders);
});


推荐答案

获取警报的原因是未定义,因为您尚未定义 $ scope.sliders http 请求是异步所以 alert($ scope.sliders); 获取数据之前的函数调用并将该数据设置为 $ scope.sliders

The reason for getting alert is undefined is because you haven't define $scope.sliders in controller and http request is async so alert($scope.sliders); function call before getting data from response and setting that data to $scope.sliders.

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

You get alert($scope.sliders); value only after getting success response.

其他可能性是您可以设置 $ scope.sliders = {} 然后使用 alert($ scope.sliders); 然后函数时,在警告中显示 {} 被称为 alert 显示实际回复。

Other possibility is you can set $scope.sliders = {} and then use alert($scope.sliders); which show {} in alert when then function is called alert shows actual response.

原始 plunker 基于问题

检查新的 plunker

这篇关于AngularJs http get响应未定义但数据存在于success函数内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆