0

When I call $http.get from a factory it doesn't return the JSON object I need but a different one.

Here's my code:

var cart = angular.module('cart', []);

cart.factory('getItems',['$http', function($http){
    return{ 
        get:$http.get('index.php').
            success(function(data){
                return data;
            })
        }
}]);


cart.controller("TableCtrl", ['$scope', 'getItems', function($scope, getItems){
    console.log(getItems.get);
}]);

now this is the JSON object that it should return:

[{"id":"1","name":"Cap"},{"id":"2","name":"Coat"},{"id":"3","name":"Shoes"}]

And this is what I get when I console.log

d {$$state: Object, success: function, error: function, then: function, catch: function…}

everything runs fine if I run the $http.get inside the controller, but if I place it in a factory it just doesn't.

2 Answers 2

5

It's returning a promise, which you need to resolve

In your controller..

getItems.get().then(function(response) {
    console.log(response.data)
});

More information, see The Promise Api

Angular $q docs

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you this is correct. Can you tell me please, in a nutshell, what are promises and how do they apply in this case?
You're welcome, and please remember to accept the answer so we can both gain a little rep @Kris
@Kris if this is correct why did you accept the late answer?
0

$http.get returns a promise not the data itself. Your current use of the success function is not going to get data back.

In your factory:

return{ get: $http.get('myurl')};

Then consuming it should be:

myFactory.get().success(response){
     var mydata = response.data; 
}

Success is just an addition to the promise. I like to just use .then like standard, unadorned promises.

When I first heard about promises, I thought it meant you could use it without having to provide any sort of callback-like code on your consuming end. That is not true, but promises are still super awesome and very powerful. The coolest thing is that you can keep a promise around, and anybody can add a .then to the promise. Whoever does will get their code executed as soon as the asynchronous request finishes, or right away if it has already finished. So promises let you not have to worry about asynchronous behavior, but you still have to use what is basically its more powerful version of callbacks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.