javascript - AngularJs http get response is undefined 但是数据存在于成功函数中

标签 javascript angularjs

我是 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、'undefined' 和 2 的警报 但是 $scope.sliders 有数据。因为一旦我调整屏幕大小它就可以工作,而且我可以在

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

最佳答案

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

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

另一种可能性是你可以设置$scope.sliders = {}然后使用 alert($scope.sliders);显示{}then时处于警戒状态函数称为 alert显示实际响应。

原创 plunker基于问题

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

关于javascript - AngularJs http get response is undefined 但是数据存在于成功函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33406577/

相关文章:

javascript - AngularJs + typescript 指令依赖注入(inject)

javascript - 从数组中删除 NaN

angularjs - Bootstrap-UI Typeahead 在结果列表中显示多个属性?

javascript - mongodb stitch 返回所有字段

javascript - Node.js 同步循环

javascript - 比较 Javascript 范围

javascript - 如何从 map 对象中删除具有对象键的对象?

mysql - 如何将rest api和yii2中两个数据库表的关系数据显示为json格式

php - 为什么我不能使用angularjs向mysql数据库插入数据

AngularJS 嵌套指令