AngularJS 工厂 http 返回空 [英] AngularJS factory http returns empty

查看:31
本文介绍了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.

推荐答案

你应该修改你的代码以返回一个promise并使用控制器中的值请参阅虚拟修改代码

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆