[英]AngularJS: assign $http.get data to variable
I try to assign data from $http.get to variable in my controller. 我尝试将$ http.get中的数据分配给我的控制器中的变量。
$http.get(URL).success(function (data) {
$scope.results = data;
console.log('results in $http.get :'+ $scope.results);
});
console.log('results after http.get'+ $scope.results);
First console log print data from get. 第一个控制台日志打印数据来自get。 After $http.get(url).success $scope.results prints as undefined.
在$ http.get(url).success $ scope.results打印为undefined之后。
This is because $http.get
is asynchronous. 这是因为
$http.get
是异步的。 So your code is not put on hold until ajax request is complete, instead it will execute the rest of the code. 因此,在ajax请求完成之前,您的代码不会被搁置,而是执行其余代码。 So your second
console.log
will be executed before the ajax request completes. 所以你的第二个
console.log
将在ajax请求完成之前执行。 At this point there is no scope variable called $scope.results
, which is defined only after the request completes, that's why it prints undefined
. 此时,没有名为
$scope.results
范围变量,它仅在请求完成后定义,这就是它打印undefined
的原因。 Your first console.log
will print only after $http
ajax completes with success, at this point you have $scope.results
which is assigned to data
coming from backend. 您的第一个
console.log
将仅在$http
ajax成功完成后打印,此时您有$scope.results
,它被分配给来自后端的data
。
$http
is an asynchronous
function. $http
是一个asynchronous
函数。 It returns instantly however it returns a promise
not a real result. 它立即返回,但它返回的
promise
不是真实的结果。 When the request is completed onsuccess
is called. 请求完成
onsuccess
将调用onsuccess
。
The second (the one outside the call) console.log
executes before $http
returns. 第二个(调用之外的)
console.log
在$http
返回之前执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.