Angular js returning undefined object from factory
Asked Answered
A

2

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

Annamaeannamaria answered 29/7, 2013 at 20:21 Comment(0)
M
8

You need to either use a callback function or just put a return before $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;
     }
 });
Millibar answered 29/7, 2013 at 21:28 Comment(0)
S
2

$http.get is asynchronous so at the time you try to access it (inside your controller) it may not have data (hence you get undefined).

To solve this I use .then() after I call the factory method from my controller. Your factory then would look something like:

myApp.factory('ListFactory', function($http) {
    return {
        get: function() {
            $http.get('http://example.com/list');
        }
    };
});

And your controller:

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

Hope it helps

Sining answered 4/2, 2015 at 5:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.