【问题标题】:AngularJS factory http returns emptyAngularJS 工厂 http 返回空
【发布时间】:2023-03-23 01:59:01
【问题描述】:

我是第一次尝试 AngularJS。我正在使用工厂从 http-get 请求中获取 JSON 数据,但在 ajax-request 完成之前,该对象返回为空。

工厂:

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 响应之前返回照片数组一样。

【问题讨论】:

    标签: http angularjs factory angularjs-service


    【解决方案1】:

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

    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;
       });
    };
    

    【讨论】:

    • 我可以用这个作为post方法吗?
    【解决方案2】:

    使用 q promise 库意味着您的成功函数可以继续为您服务:

    app.factory('Data', function ($http, $q) {
        return {
            ajaxItems: function () {
                var deferred = $q.defer();
                $http({ method: "POST", url: "/Home/GetSearchResults" })
                    .success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                return deferred.promise;
            }
        }
    });
    
    app.controller('ResultsCtrl', ['$scope', 'Data', function ($scope, Data) {
        $scope.get = function () {
            $scope.items = Data.ajaxItems();
            //the model returns a promise and THEN items
            $scope.items.then(function (items) {
                $scope.items = items;
            }, function (status) {
                console.log(status);
            });
        };
    }]);
    

    【讨论】:

    • 谢谢。我认为这是最好的方法。它使控制器保持精简。
    • 谢谢,这就是我想要的。 :)
    • 我们如何处理错误?出现错误时项目的价值是多少?
    【解决方案3】:

    $http 相比,使用$resource 可以实现您想要的,并且给您更多的控制权

    (不要忘记将ngResrouce 作为应用程序的依赖项。)

    myDemo.factory('photosFactory', function($resource) {
        var factory = {};
    
        factory.getPhotos = $resource('content/test_data.json', {}, {
            'query': {method: 'GET', isArray: true}
        });
        return factory;
    });
    
    controllers.AppCtrl = function($scope, $location, $http, photosFactory) {
        $scope.photos = [];
        init();
        function init() {
            $scope.photos = photosFactory.getPhotos.query();
        }
    };
    

    【讨论】:

    • 与@Ajay beniwal 回答相比,这样做有什么优势?
    • 当使用$resource时,你的每张照片都是AngularJs resource对象,其中包含$save$delete等方法,这使得使用Restful api更容易。
    猜你喜欢
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    相关资源
    最近更新 更多