Called service data

Hi,

I using this to save data to the service and called it again in the same controller after save it. But it didn’t have value for the service. When i call the service again in another controller, it gave me the result i want.

.controller('HomeCtrl', function ($scope) {
    $http.get(URL).success(function(data){
       Service.thisData(data);

       Service.getData(); // value = 1000
    });

    // call save data from service
    // i didn't get any data from the service
    Service.getData(); // value = undefined
};

So how do i get the data from service except inside the http.get??

Thanks.

Hey there!

One way to do this would be to use promises in your service. Here’s how it would look with your example.

.factory('Service', [
    '$q',
    function($q){
        return getData: function() {
            var def = $q.defer();
            $http.get('http://example.com')
                .success(function(data){
                    def.resolve(data);
                })
                .error(function(data){
                  def.reject(data);
                });

            // Return the promise
            return def.promise
        }
    }
]);

From here, you could use the factory in your controller like so:

Service.getData().then(function(data){
    console.log('Data from a service!', data);
});

Let me know if that helps out :slight_smile:

Awesome, it works. Thanks :smile: