我是 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/