Return values ​​from AngularJS services

I am trying to return a value from my AngularJs service to my controller where ever I pass it inside the controller. It passes the object and also writes data to 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 "items.Tweets [1] .FAVORITE_COUNT" when calling the function.

Thank you in advance

+3


source to share


2 answers


You can create a promise of the requested data using a method then

that getAll

will know what to do before the API responds.



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;
        }

    }

}];

      

+1


source


One way is to create a promise and resolve it when the request is successful. Remember to discard 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 can return the promise from $ http.get:



 return $http.get(path);

      

How the method is a call to getAll

0


source







All Articles