[英]AngularJs http get response is undefined But the data is present inside success function
Am new to angular. 角色很新。 I have tried to get the json response from http get method. 我试图从http get方法获取json响应。
My code is, 我的代码是,
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);
am getting the alert like 1, 'undefined' and 2 but the $scope.sliders has the data. 我收到警告,如1,'undefined'和2,但$ scope.sliders有数据。 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);
});
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);
获取警报的原因是undefined
的原因是你没有在控制器中定义$scope.sliders
而http
请求是异步所以alert($scope.sliders);
function call before getting data
from response and setting that data to $scope.sliders
. 在从响应中获取data
并将该数据设置为$scope.sliders
之前进行函数调用。
You get alert($scope.sliders);
你得到alert($scope.sliders);
value only after getting success response. 获得成功回应后才有价值。
Other possibility is you can set $scope.sliders = {}
and then use alert($scope.sliders);
其他可能性是你可以设置$scope.sliders = {}
然后使用alert($scope.sliders);
which show {}
in alert when then
function is called alert
shows actual response. 这表明{}
中,当警报then
函数被调用alert
显示实际的响应。
Original plunker based on issue 基于问题的原始plunker
Check comments and updated code in new plunker 检查新plunker中的注释和更新代码
$http
is a asynchronous call, so what happens is that you have triggered a http call at line number 6 while it gets the response the line number 10 will be executed since all http
calls in angular are asynchronous. $http
是一个异步调用,所以会发生的是你在第6行触发了一个http调用,而它得到了第10行将被执行的响应,因为angular中的所有http
调用都是异步的。
That is why you are getting undefined
这就是你undefined
If you want to do anything after the response just do the stuff within the http promise ie. 如果你想在响应之后做任何事情,只需要在http promise中做一些事情,即。 within the .then
function block like as shown below 在.then
功能块中,如下所示
getdata.getlist()
.then(function(response){ // http promise block
$scope.sliders = response.data;
console.log($scope.sliders);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.