AngularJs http get响应未定义但数据存在于success函数内

Ana*_*r R 4 javascript angularjs

角色很新.我试图从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);
Run Code Online (Sandbox Code Playgroud)

我收到警告,如1,'undefined'和2,但$ scope.sliders有数据.因为它在我调整屏幕大小时工作,而且我可以在内部获得正确的警报

getdata.getlist().then(function(arrItems) {
  $scope.sliders = arrItems;         
  alert($scope.sliders);
});
Run Code Online (Sandbox Code Playgroud)

Sar*_*sai 6

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

alert($scope.sliders);只有在获得成功回复后才能获得价值.

其他可能性是您可以设置$scope.sliders = {}然后在调用函数时alert($scope.sliders);显示{}警报中的哪个节目显示实际响应.thenalert

基于问题的原始plunker

检查新plunker中的注释和更新代码