0

I'm trying use $http.get() in a factory to retrieve a value which will be processed further in a controller.

appFac.factory('CompletedJobs',function($http){
var result;
    return{
        getJobs : function(webserviceurl){
            $http.get(webserviceurl).success(function(data){
                result = data;
            })
            .error(function(err){
                result = '';
            });
            return result;
        }
    }
})

appCtrl.controller('Ctrl',function(CompletedJobs){
    var data = CompletedJobs.getJobs('some url');
    // some other logic based on data
});

Due to the asynchronism, by the time the data becomes available inside the factory method, it is of no use to the controller because the factory method has already returned undefined.

Can anyone help me work out how to get the data from the factory method so it can be used by the controller?

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
Ranjan Sarkar
  • 61
  • 1
  • 2
  • 5
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil Apr 05 '16 at 02:33

2 Answers2

1

In your factory you should return the promise of success or error instead of explicitly returning the result because that will be returned before your promise get resolved. Modify you factory like this.

appFac.factory('CompletedJobs',function($http, $q){
    return{
        getJobs : function(webserviceurl){
            var deferred = $q.defer();
            $http.get(webserviceurl).then(function(response){
                deferred.resolve(response.data);
                return deferred.promise;
            });
        }
    }
})

appCtrl.controller('Ctrl',function(CompletedJobs){
    var data = CompletedJobs.getJobs('some url');
    // some other logic based on data
});

This should work for you.

Sardesh Sharma
  • 1,671
  • 1
  • 12
  • 14
0

In the factory return the promise.

appFac.factory('CompletedJobs',function($http){
return {
    getJobs : function(webserviceurl){
        //return the promise
        return $http.get(webserviceurl);
    }
};

In the controller chain from the promise.

appCtrl.controller('Ctrl',function(CompletedJobs){
    var promise = CompletedJobs.getJobs('some url');

    promise.then( function onFulfilled(result) {
        var data = result.data
        // some other logic based on data
    }).catch( function onRejection(result) {
        console.log(result.status);
    });
}); 
georgeawg
  • 48,608
  • 13
  • 72
  • 95