Charan Cherry Charan Cherry - 2 months ago 10
AngularJS Question

Unable to return value from factory to service angularJS

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.

Answer

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