AngularJS厂HTTP返回空 [英] AngularJS factory http returns empty
本文介绍了AngularJS厂HTTP返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想,第一次AngularJS。我从HTTP-GET请求,使用工厂获取JSON数据,但对象返回空,AJAX请求之前完成。
I'm trying AngularJS for the first time. I'm getting JSON data from a http-get request using a factory, but the object is returned empty, before the ajax-request is done.
厂址:
myDemo.factory('photosFactory', function($http) {
var photos = [];
var factory = {};
factory.getPhotos = function() {
$http({
url: 'content/test_data.json',
method: 'GET'
}).success(function(data, status, headers, config) {
photos = data;
return photos;
});
};
return factory;
});
控制器:
controllers.AppCtrl = function($scope, $location, $http, photosFactory) {
$scope.photos = [];
init();
function init() {
$scope.photos = photosFactory.getPhotos();
}
};
这是什么我已经出来了。当控制器设置$ scope.photos,该值是空的,因为如果它返回的照片阵列之前,它与Ajax响应得到填充。
This is what I've come up with. When the controller set $scope.photos, the value is empty as if it returns the photos array before it get populated with the ajax response.
推荐答案
您应该修改code返回一个承诺,使用控制器请值为看到假人修改code
You should modify your code to return a promise and use the value in controller pls see dummy modified code
myDemo.factory('photosFactory', function($http) {
return{
getPhotos : function() {
return $http({
url: 'content/test_data.json',
method: 'GET'
})
}
}
});
和控制器 -
controllers.AppCtrl = function($scope, $location, $http, photosFactory) {
$scope.photos = [];
photosFactory.getPhotos().success(function(data){
$scope.photos=data;
});
};
这篇关于AngularJS厂HTTP返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文