我正在尝试将 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;
}
]);
最佳答案
对$http
的异步调用返回一个promise,但函数本身返回currentUser
,即null
。如果 currentUser
为 null
,则需要返回 $http
promise ,或者返回包含在 promise 中的 currentUser
,如果不是null
:
angular.module('myWebApp.services')
.factory('CurrentUserFactory', ['SettingsFactory', '$http', '$q', function(SettingsFactory, $http, $q) {
var CurrentUserFactory = {};
var currentUser = null;
CurrentUserFactory.GetCurrentUser = function() {
if (!currentUser) {
return $http.get(SettingsFactory.myAPIUrl + 'api/users/current', { withCredentials: true }).then(function (response) {
currentUser = response.data;
return response.data;
});
}
return $q.resolve(currentUser);
}
return CurrentUserFactory;
}
]);
用法:
因为该函数返回一个 promise ,所以您需要一个 .then()
阻止获取结果:
CurrentUserFactory.GetCurrentUser().then(function(currentUser) {
console.log(currentUser);
});
关于javascript - Angular 工厂函数总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40981873/