0

I want to create a factory that always returns the json object retrieved from a webservice:

angular.module('test').factory('myService', myService);
myService.$inject = ['$http'];

function myService($http) {
    var urlBase;

    return {
        getContent: function(id) {
            return $http.get(urlBase).then(function(response) {
                return response.data;
            });
        }
    };
}

When I call MyService.getContent();, I'm not getting the JSON object, but an object with $$state and __proto__.

Why? How can I fore the factory to directly return the content only?

Note: I know I could write

MyService.getContent().then(function(response) { console.log(response); });

but this way I'd always have to repeat the then... function statement when I access the factory.

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • What happens if you open the url (urlBase) in a browser? – jbrown Feb 09 '16 at 13:39
  • 2
    This is why promises are there for. How would you ensure the sequence if you won't use promsie returned by $http in controller. In case you wan't to setup some model with the data returned from service. – Diljohn5741 Feb 09 '16 at 13:40

2 Answers2

2

You can't return the result of an asynchronous function. Your return response.data; statement is just exiting the promise .then() callback. You should modify your function like so:

getContent: function(id) {
  return $http.get(urlBase);
}

And then call it like this:

MyService.getContent().then(function (response) {
  // do something with the response
});
Joe Clay
  • 33,401
  • 4
  • 85
  • 85
  • I posted this before your edit, but it still applies - there's no way to synchronously return a piece of data that's retrieved asynchronously! – Joe Clay Feb 09 '16 at 13:41
0

That is because you are returning a promise that has already been resolve and not the promise instance. Just returning

$http.get(urlBase)

from your getContent function should do the trick :)

shanks
  • 912
  • 10
  • 23