我试图将currentUser对象存储在工厂中,以便可以在我的应用程序中访问它。但是,只要我调用CurrentUserFactory.GetCurrentUser(),它就会返回null。我已经验证过,一切都很好,服务器端正在接收用户对象。但它总是返回null。角度工厂函数总是返回空
angular.module('myWebApp.services')
.factory('CurrentUserFactory', ['SettingsFactory', '$http', function(SettingsFactory, $http) {
var CurrentUserFactory = {};
var currentUser = null;
CurrentUserFactory.GetCurrentUser = function() {
if (!currentUser) {
$http.get(SettingsFactory.myAPIUrl + 'api/users/current', { withCredentials: true }).then(function (response) {
currentUser = response.data;
});
}
return currentUser;
}
return CurrentUserFactory;
}
]);
这是一个AJAX调用 - 你不能从它返回 - 哟你需要使用承诺或回调。 – tymeJV
您可以使用对象初始化您的'currentUser',然后将所有响应字段复制到该对象。然后你会得到最终用户。 –
@tymeJV'.then'不是承诺吗? – Legion