Skip to content Skip to sidebar Skip to footer

Expose An Object From An Angular Service Using Getter Function Return Undefined

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 th

Solution 1:

Closure issue. Try

app.factory('authService', function($http){
    var authServ = {};
    that = this; //that captures the current closurethis.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.

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

Post a Comment for "Expose An Object From An Angular Service Using Getter Function Return Undefined"