我试图使用promise将对象返回到下面函数中定义的数据变量。如果我在控制器中使用promise并使res = $ scope.data,它工作正常,但我想的越多,在$ scope中提供此信息并不是必需的,因为用户登录信息/会话ID不应更改。
(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};
}]);
})();
问题是,在工厂中尝试此操作时,res会将其作为空对象进行安慰。我尝试的是什么/明智的?
答案 0 :(得分:0)
您将数据定义为空对象
//other variables set successfully by another method
var data = {}, // <-- here
然后将res
设置为data
(空对象)
res = data; // <-- data is defined as empty object above
console.log("sessionId", res);
难怪为什么它会记录一个空对象