AngularJS $ HTTP返回值 [英] AngularJS $http return value
问题描述
我是新来的 AngularJS
键,只知道AngularJS的基本知识。我想回到从 $ HTTP
的值。这就是 $ HTTP
应的值返回我的应用程序的全局变量。
I am new to AngularJS
and only aware of the basics of AngularJS. I want to return a value from $http
. That is $http
should return a value to the global variable of My Application.
我已经试过这样:
var sessionValues = null;
var AdminController = angular.module('AdminController', []);
AdminController.controller('LoginController', ['$scope', '$http','$location',
function ($scope, $http, $location){
$http({
method: "post",
url: "API/MyPage.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
sessionValues = eval(data);
console.log(sessionValues); /*Returns desired string*/
}).error(function(){
$scope.message="Some error has occured";
});
console.log(sessionValues); /*Returns null */
}
]);
我试图用 $ rootScope
,但没有成功。
据我所知,这是因为它是一个异步调用,但我怎么能取在JS的全局变量的值。?
I understand that this is because it is an asynchronous call, but how can I fetch the value in JS's global variable.?
谁能帮我这个?
推荐答案
这个问题确实是与调用的异步性,当你试图访问变量。 的console.log
返回null,因为它被称为 $ HTTP
调用完成之前。
The problem is indeed with the async nature of call and when you are trying to access the variable. console.log
returns null because it gets called before the $http
call is complete.
首先,我们不污染的JavaScript全球范围内,但使用的服务\工厂,$ rootScope来访问数据。
Firstly we do not pollute the JavaScript global scope, but use services\factory, $rootScope to access data.
在,如果你想给一个变量暴露给整个角度你的情况下,最简单的方法是使用$ rootScope。事情是这样的。
In you case if you want to expose a variable to across angular, the easiest way is to use $rootScope. Something like this
AdminController.controller('LoginController', ['$scope','$http','$location','$rootScope'
function ($scope, $http, $location,$rootScope){
$http({
method: "post",
url: "API/MyPage.php",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
$rootScope.sessionValues = eval(data);
console.log($rootScope.sessionValues); /*Returns desired string*/
}).error(function(){
$scope.message="Some error has occured";
});
console.log($rootScope.sessionValues); /*Returns will always null due to async nature call*/
}
]);
您接下来要访问该变量只有在它已被填补了成功的回调,在此之前,这将是始终为空。该的console.log
总是失败。
You then have to access that variable only after it has been filled in the success call back, before that it would be always null. The console.log
would always fail.
要知道什么时候该变量的值发生了变化,你可以使用AngularJS看<一href="http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html">http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html
To know when the variable value has changed you can use AngularJS watch http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html
这篇关于AngularJS $ HTTP返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!