8

I have a controller and factory defined as below.

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

What confuses me is that I get the output undefined from my controller, and then the next line of console output is my list of objects from my factory. I have also tried changing my controller to

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

But I receive the error

TypeError: Cannot call method 'then' of undefined

Note: I found this information on using a factory through http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html

4

2 回答 2

8

您需要使用回调函数或只是在之前放一个 return$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;
     }
 });
于 2013-07-29T21:28:50.633 回答
2

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

希望能帮助到你

于 2015-02-04T05:21:27.077 回答