Krimson
Krimson

Reputation: 7674

class variable in service in angularjs

Im developing a simple Account Management page where a user can login, register etc

Each section has its own controller. i.e The login page has a login controller. These controllers share a common service AccountService to handle the login, register mechanics.

This is my AccountService:

app.service('AccountService', function($http){
    var user = {};

    this.isLoggedIn = function(){
        return user.isAuth;
    };

    this.login = function(user, callback){
      //...//  
      if(success){
          //Mark user as authenticated
          user.isAuth = true;  
      }
    };  
});

As you can see, if I login by doing AccountService.login(user) the variable user.isAuth is set to true upon success. BUT the problem is if I then call AccountService.isLoggedIn() I expect the function to return true but it returns undefined

For example if I do:

app.controller('LoginController', function($scope, AccountService) {
    $scope.login = function(user) {
        //Do Login
        AccountService.login(user, function(r){
            result = r;
        });                            //At this point user.isAuth should be true

        //Check if user is logged in
        console.log(AccountService.isLoggedIn()); //This returns false
    }
}

So how do I persist the variables in a service?


Edit @itcouldevenbeaboat suggested that the value is not set before the second function is called due to the asynchronous call. However it still doesn't work when I separate the function call from each other like so:

app.controller('LoginController', function($scope, AccountService) {
    $scope.login = function(user) {
        //Do Login
        AccountService.login(user, function(r){
            result = r;
        });                            //At this point user.isAuth should be true
    }
    $scope.isAuth = function(){
        //Check if user is logged in
        console.log(AccountService.isLoggedIn()); //This STILL returns false
    }
}

I still get a false when I call the login function and then the isAuth function on the LoginController

Upvotes: 1

Views: 216

Answers (1)

Code Whisperer
Code Whisperer

Reputation: 23662

Your login function is asyncronous. So the console.log is actually running before the data comes back.

Try this instead,

$scope.login = function(user) {
    //Do Login
    AccountService.login(user, function(r){
        result = r;
        console.log(AccountService.isLoggedIn()); //This returns true
    });                            
}

Upvotes: 2

Related Questions