2

I'm trying to understand some best practices in Angular and want to combine the mentioned pattern in a factory to retrieve data from a REST API:

function feedFactory($resource) {
    var service = {
        feedData: [],
    };
    getFeedFromApi();

    return service;

    function getFeedFromApi() {
        var feed = $resource('http://footballdb.herokuapp.com/api/v1/event/de.2014_15/teams?callback=JSON_CALLBACK', {}, {
          query: {
            method: 'JSONP'
          }
        });

        feed.query().$promise.then(function(result) {
            service.feedData = result.toJSON();
        });
    }
}

Unfortunately, I can't set the feedData variable of the service object although I receive a valid promise object with data.

1 Answers1

2

The way you deal with asynchronous requests is incorrect. Response is not available bt the time you return it. So it's undefined.

Usually factories in angular look like this:

function feedFactory($resource) {

    var service = {
        getFeedFromApi: getFeedFromApi
    };

    function getFeedFromApi() {

        var feed = $resource('http://footballdb.herokuapp.com/api/v1/event/de.2014_15/teams?callback=JSON_CALLBACK', {}, {
            query: {
                method: 'JSONP'
            }
        });

        return feed.query().$promise.then(function (result) {
            return result.toJSON(); // you really need to convert response to string?
        });
    }

    return service;
}

And then you use them in controller this way:

feedFactory.getFeedFromApi().then(function(data) {
    // do something with data
});
Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • 1
    Doesn't it have to be `return feed.query().$promise.then(...)});` in the factory? –  Oct 14 '14 at 12:45