微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax – Angular js从工厂返回未定义的对象

我有一个控制器和工厂定义如下.
myApp.controller('ListController',function($scope,ListFactory) {
    $scope.posts = ListFactory.get();
    console.log($scope.posts);
});

myApp.factory('ListFactory',function($http) {
    return {
        get: function() {
            $http.get('http://example.com/list').then(function(response) {
                if (response.data.error) {
                    return null;
                }
                else {
                    console.log(response.data);
                    return response.data;
                }
            });
        }
    };
});

令我困惑的是,我从控制器获取未定义的输出,然后控制台输出的下一行是我工厂的对象列表.我也尝试过将控制器更改为

myApp.controller('ListController',ListFactory) {
    ListFactory.get().then(function(data) {
        $scope.posts = data;
    });
    console.log($scope.posts);
});

但我收到错误

TypeError: Cannot call method 'then' of undefined

注意:我通过http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html找到了有关使用工厂的信息

你需要使用回调函数或者只是在$http.get之前放回一个
return $http.get('http://example.com/list').then(function (response) {
     if (response.data.error) {
         return null;
     } else {
         console.log(response.data);
         return response.data;
     }
 });

原文地址:https://www.jb51.cc/ajax/160009.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐