【问题标题】:Expose an object from an Angular service using Getter function return undefined使用 Getter 函数返回未定义的 Angular 服务公开对象
【发布时间】:2026-02-10 17:40:01
【问题描述】:

代码如下:

authServ.getUser() 从任何地方返回 {}(一个空对象,对应于这个 var 的声明),即使在我根据这个 [问题][1] 对返回语法进行了修改之后.

谁能告诉我这是什么问题?,我看不出它不应该工作的原因

app.factory('authService', function($http){
    var authServ = {};
    var currentUser = {};
        authServ.authUser = function(){
            return $http.head('/users/me', {withCredentials: true});
        },
        authServ.getUser =  function(){
            return currentUser;
        },
        authServ.setCompany =  function(companyId){
            currentUser.company = companyId;
        }
        authServ.loadCurrentUser = function(){
            $http.get('/users/me', {withCredentials: true}).
            success(function(data, status, headers, config){
                console.log(data);
                currentUser.company = currentUser.company ? currentUser.company : data.main_company;
                currentUser.companies = [];
                for(var i in data.roles){
                    currentUser.companies.push(data.roles[i]['company_name']);
                    if(data.roles[i]['company'] == currentUser.company)
                        currentUser.role = data.roles[i]['role_type'];
                }
                console.log(currentUser);
            }).
            error(function(data, status, headers, config){
                currentUser.role = 'guest';
                currentUser.company = 1;
            });
        }

        return authServ;
});

工作代码:

run(function($rootScope, $location, $http, authService){
$rootScope.$on("$routeChangeError", function(event, current, previous, rejection){
    if(rejection.status == 401)
        $location.path('/login');
})
authService.loadCurrentUser().then(function(){
    console.log(authService.getUser());
});


});
app.factory('authService', function ($http) {
    authServ = {};
    that = this;
    that.currentUser = {};
    authServ.authUser = function () {
        return $http.head('/users/me', {
            withCredentials: true
        });
    },
    authServ.getUser = function () {
        return that.currentUser;
    },
    authServ.setCompany = function (companyId) {
        that.currentUser.company = companyId;
    },
    authServ.loadCurrentUser = function () {
        return $http.get('/users/me', {
            withCredentials: true
        }).
        success(function (data, status, headers, config) {
            console.log(data);
            that.currentUser.company = that.currentUser.company ? that.currentUser.company : data.main_company;
            that.currentUser.companies = [];
            for (var i in data.roles) {
                that.currentUser.companies.push(data.roles[i]['company_name']);
                if (data.roles[i]['company'] == that.currentUser.company) that.currentUser.role = data.roles[i]['role_type'];
            }
            console.log(that.currentUser);
        }).
        error(function (data, status, headers, config) {
            that.currentUser.role = 'guest';
            that.currentUser.company = 1;
        });
    }
    return authServ;
});

小提琴: http://jsfiddle.net/V9Ex6/1/

【问题讨论】:

  • return that;改成'return authServ;'
  • 显然,我完全忘记了我正在异步加载这些数据的事实,为了从外部访问这些数据,我应该从 loadUser 函数返回 promise 对象,然后使用.then() 函数为它的解析分配一个回调。编辑了代码和小提琴,谢谢你帮我sza
  • @sza 说我想在选择菜单中呈现公司,考虑到我从 XHR 请求中获取这些数据,我该怎么做?顺便说一句,非常感谢您迄今为止的所有帮助
  • 我在网上找到了一个demo,希望对你有帮助。 jsfiddle.net/2JWb2/5

标签: javascript angularjs angularjs-directive


【解决方案1】:

关闭问题。试试

app.factory('authService', function($http){
    var authServ = {};
    that = this; //that captures the current closure
    this.currentUser = {};
    authServ.getUser =  function(){
        return that.currentUser;
    },

并更改loadCurrentUser 以使用that.currentUser 访问变量。

编辑

authService.loadCurrentUser();
console.log(authService.getUser());

由于loadCurrentUser 异步加载用户,因此无法保证打印出用户。您应该更改loadCurrentUser 以获取回调函数以获取用户值。

希望对你有帮助。

【讨论】:

  • 那我应该返回什么?,这个,那个,还是 authServ?
  • 使用that,使其保持一致。
  • Uncaught TypeError: Object # has no method 'loadCurrentUser' when trying to call loadCurrentUser() from the app of the run function,我已经发布了更新的代码,谢谢你的时间
  • 你怎么称呼它的?像 authService.loadCurrentUser() ?
  • authServ.loadCurrentUser = function(){...} 我应该在这种情况下使用它吗?,我有点困惑
【解决方案2】:

试试这个,请注意我还没有测试过:)

app.factory('authService', function($http){
    return {
        authUser: function(){
            return $http.head('/users/me', {withCredentials: true});
        },
        getUser:  function(){
            return currentUser;
        },
        setCompany:  function(companyId){
            currentUser.company = companyId;
        },
        loadCurrentUser: function(){
            $http.get('/users/me', {withCredentials: true}).
            success(function(data, status, headers, config){
                console.log(data);
                currentUser.company = currentUser.company ? currentUser.company : data.main_company;
                currentUser.companies = [];
                for(var i in data.roles){
                    currentUser.companies.push(data.roles[i]['company_name']);
                    if(data.roles[i]['company'] == currentUser.company)
                        currentUser.role = data.roles[i]['role_type'];
                }
                console.log(currentUser);
            }).
            error(function(data, status, headers, config){
                currentUser.role = 'guest';
                currentUser.company = 1;
            });
        }
     }
});

【讨论】:

  • 'Uncaught ReferenceError: currentUser is not defined',在为这个变量添加声明后,我遇到了和我的代码一样的问题。感谢您抽出宝贵时间发布您的答案!