简体   繁体   English

AngularJS:将$ http.get数据分配给变量

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM