我正在尝试使用$ http,但为什么它会返回null结果?
angular.module('myApp')
.factory('sender', function($http) {
var newData = null;
$http.get('test.html')
.success(function(data) {
newData = data;
console.log(newData)
})
.error(function() {
newData = 'error';
});
console.log(newData)
return newData
})
控制台说:http://screencast.com/t/vBGkl2sThBd4。为什么我的newData首先为null然后定义?如何正确地做到这一点?
答案 0 :(得分:20)
正如YardenST所说,$http
是异步的,因此您需要确保所有依赖于$http.get()
返回的数据的函数或显示逻辑都得到相应的处理。实现此目的的一种方法是利用$http
返回的“承诺”:
var myApp = angular.module('myApp', []);
myApp.factory('AvengersService', function ($http) {
var AvengersService = {
getCast: function () {
// $http returns a 'promise'
return $http.get("avengers.json").then(function (response) {
return response.data;
});
}
};
return AvengersService;
});
myApp.controller('AvengersCtrl', function($scope, $http, $log, AvengersService) {
// Assign service to scope if you'd like to be able call it from your view also
$scope.avengers = AvengersService;
// Call the async method and then do stuff with what is returned inside the function
AvengersService.getCast().then(function (asyncCastData) {
$scope.avengers.cast = asyncCastData;
});
// We can also use $watch to keep an eye out for when $scope.avengers.cast gets populated
$scope.$watch('avengers.cast', function (cast) {
// When $scope.avengers.cast has data, then run these functions
if (angular.isDefined(cast)) {
$log.info("$scope.avengers.cast has data");
}
});
});
答案 1 :(得分:5)
此JavaScript代码是异步的。
console.log(newData)
return newData
在success
newData = data;
console.log(newData)
因此,第一次,newData为null(您将其设置为null)
当返回http响应时(在成功内部),newData获取其新值。
这在Javascript中非常常见,您应该在success
内完成所有工作。