我是有角度的新手。我尝试从 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);
});
收到警报的原因是undefined
is 因为你还没有定义$scope.sliders
在控制器和http
请求是异步的所以alert($scope.sliders);
获取之前的函数调用data
从响应并将该数据设置为$scope.sliders
.
You get alert($scope.sliders);
仅在获得成功响应后才有价值。
另一种可能性是你可以设置$scope.sliders = {}
然后使用alert($scope.sliders);
哪个节目{}
处于警戒状态时then
函数被调用alert
显示实际响应。
原来的plunker http://plnkr.co/edit/moOfwxFNM5ttH9wBzzvk?p=preview基于问题
检查 new 中的注释和更新的代码plunker http://plnkr.co/edit/UsKZbhVVeGiRipU9BVSr?p=preview
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)