Angular工厂函数始终返回null

时间:2016-12-05 19:30:57

标签: javascript angularjs

我正在尝试将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;
        }
    ]);

1 个答案:

答案 0 :(得分:3)

$http的异步调用返回一个promise,但函数本身返回currentUser,即null。如果$httpcurrentUser,则需要返回null承诺,如果不是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);
});