简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM