someoneHere
someoneHere

Reputation: 353

Can you use a promise .then() within an Angular factory?

I'm trying to use a promise to return an object to the data variable defined in the function below. It works fine if I use the promise in the controller and make res = to $scope.data, but the more I thought about, it's not really necessary to have this information in $scope, since the users login information / session ID should not change.

(function(){
    'use strict';

angular.module('csMgmtApp')
    .factory('agentFactory', ['$http', function($http){

     //other variables set successfully by another method

        var data = {},
            result = {},
            access_token = result.access_token,
            baseURIc = result.resource_server_base_uri;


       function startSession(startSessionPayload){
            var startSessionPayload = startSessionPayload,
                access_token = result.access_token,
                baseURIc = result.resource_server_base_uri;

            return $http({
                'url': baseURIc + 'services/v6.0/agent-sessions',
                'method': 'POST',
                'headers': {'Authorization': 'bearer ' + access_token, 'content-Type': 'application/json'},
                'data': startSessionPayload
            }).then(function(res){
                res = data;
                console.log("sessionId", res);
            });
        }
          return {startSession:startSession};
}]);

})();

The problem, is that when attempting this in the factory, res consoles out as an empty object. Is what I'm attempting possible / the sensible?

Upvotes: 0

Views: 227

Answers (1)

Endless
Endless

Reputation: 37855

you are defining data to be a empty object

 //other variables set successfully by another method

    var data = {}, // <-- here

and then after you set the res to be data (empty object)

            res = data; // <-- data is defined as empty object above
            console.log("sessionId", res); 

no wonder why it logs a empty object

Upvotes: 0

Related Questions