3

I am trying to return a value from my AngularJs service to my controller where ever I pass it inside the controller.It does pass the object and also log the data in the console. Here is my code:

angular.module('demoService',[])
.factory('myService',
function($http) {
return {
    getAll: function (items) {
        var path = "http://enlytica.com/RSLivee/rest/census"
        $http.get(path).success(function (items) {

        console.log(items.Tweets[1].FAVOURITE_COUNT);

       });
    }
}
});

How do i return the "items.Tweets[1].FAVOURITE_COUNT" on function call.

Thanks in advance

2 Answers 2

1

You can create a promise of the data queried, by using the method then , getAll will know what to do before the response of the API.

angular.module('demoService')
.factory('myService', ['$http', 
    function ($http) {

        function getAll (items) {
            var path = "http://enlytica.com/RSLivee/rest/census"
            return $http.get(path).then(
                function (res) {
                    return res;
                 });
        }

        return {
            getAll: getAll;
        }

    }

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

Comments

0

One way is to create a promise and resolve it when the request is success. Do not forget to reject it otherwise.

angular.module('demoService',[])
.factory('myService',
function($q, $http) {
return {
    getAll: function (items) {
        var defer = $q.defer();
        var path = "http://enlytica.com/RSLivee/rest/census"
        $http.get(path).success(function (items) {

          defer.resolve(items.Tweets[1].FAVOURITE_COUNT);
          console.log(items.Tweets[1].FAVOURITE_COUNT);

       });

       return defer.promise;
    }
}
});

Or you could return the promise from $http.get:

 return $http.get(path);

As the method is call getAll

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.