Ajax 从工厂返回未定义的对象

Ajax 从工厂返回未定义的对象,ajax,angularjs,factory,angularjs-factory,Ajax,Angularjs,Factory,Angularjs Factory,我有一个控制器和工厂定义如下 myApp.controller('ListController', function($scope, ListFactory) { $scope.posts = ListFactory.get(); console.log($scope.posts); }); myApp.factory('ListFactory', function($http) { return { get: function() {

我有一个控制器和工厂定义如下

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', 
        function($scope, ListFactory) {
    ListFactory.get().then(function(data) {
        $scope.posts = data;
    });
    console.log($scope.posts);
});
但是我收到了错误

TypeError: Cannot call method 'then' of undefined

注意:我通过

找到了有关使用工厂的信息。您需要使用回调函数,或者在
$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;
     }
 });

$http.get是异步的,因此在您尝试访问它时(在控制器内部),它可能没有数据(因此未定义)

为了解决这个问题,我在从控制器调用工厂方法后使用.then()。然后,您的工厂将类似于:

myApp.factory('ListFactory', function($http) {
    return {
        get: function() {
            $http.get('http://example.com/list');
        }
    };
});
和您的控制器:

myApp.controller('ListController', function($scope, ListFactory) {
    ListFactory.get().then(function(response){
        $scope.posts = response.data;
    });
    // You can chain other events if required
});
希望能有帮助