Expose an object from an Angular service using Getter function return undefined

蹲街弑〆低调 提交于 2019-12-10 18:54:00

问题


here is the code:

authServ.getUser() returns {} (an empty object, which corresponds to the declaration of this var), from everywhere, even after the revision that I have made to the return syntax according to this [question][1].

Can anyone please advise what is the issue?, I don't see a reason why it shouldn't work

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;
});

WORKING CODE:

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;
});

Fiddle: http://jsfiddle.net/V9Ex6/1/


回答1:


Closure issue. Try

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

And change loadCurrentUser to access to the variable using that.currentUser.

Edit:

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

The user is not guaranteed to be printed out since loadCurrentUser loads the user asynchronously. You should change loadCurrentUser to take a callback function in order to get the user value.

Hope it helps.




回答2:


Try this, mind you I haven't tested it :)

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;
            });
        }
     }
});


来源:https://stackoverflow.com/questions/18104056/expose-an-object-from-an-angular-service-using-getter-function-return-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!