0

my factory code

.factory('appData', ['connectionManager', function($connectionManager) {
    return {
        getAppDataItem: function(apiName, params) {
            console.log('Getting value...');
            $connectionManager.sendRequest({
                'apiName': apiName,
                'params':{
                    '@key': "'" + params['@key'] + "'"
                }
            }).then(function(res){
                console.log('Retrieved data ', res.data);
                return res.data;
            });
        }
    }
}]);

my service code

            var x = appData.getAppDataItem('getItemFromAppData', {
                    '@key': 'last_emp_id'
                });
            console.log(x);

I want to assign value returned by .then() in factory to the var x in my service. But I am unable to do it. please help me. I am getting value up to .then(). After that I am unable to pass it to the service.

Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62
  • Do you get any error? apiName is passed clearly? – Aravind Sep 16 '16 at 12:13
  • 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) – Tamas Hegedus Sep 16 '16 at 12:28

1 Answers1

1

The getAppDataItem function needs to return a promise:

.factory('appData', ['connectionManager', function($connectionManager) {
    return {
        getAppDataItem: function(apiName, params) {
            console.log('Getting value...');                
            //$connectionManager.sendRequest({
            //return promise
            return $connectionManager.sendRequest({
                'apiName': apiName,
                'params':{
                    '@key': "'" + params['@key'] + "'"
                }
            }).then(function(res){
                console.log('Retrieved data ', res.data);
                return res.data;
            });
        }
    }
}]);

The client code should use the promise's .then method to access the data.

var promise = appData.getAppDataItem('getItemFromAppData', {
        '@key': 'last_emp_id'
    });
promise.then( function (x) {
    console.log(x);
});
georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • Thank you very much. Is there any other way to do it? This is fine but I want to know – Mr_Perfect Sep 16 '16 at 12:24
  • Another way is to return an object reference that will later be filled in with the data. But in that case I recommend that the promise be added to the object as a property named `$promise`. – georgeawg Sep 16 '16 at 12:30