加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:38:00 所属栏目:百科 来源:网络整理
导读:我有一个控制器和工厂定义如下. myApp.controller('ListController',function($scope,ListFactory) { $scope.posts = ListFactory.get(); console.log($scope.posts);});myApp.factory('ListFactory',function($http) { return { get: function() { $http.ge
我有一个控制器和工厂定义如下.
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;
     }
 });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读