0

I have following code in service:

function (Api) {
    var user = null;
    return {
        checkUser: function() {
            Api.checkAuth().then(function(userObj) {
                user = userObj;
            })
        }, 
        isLogin: function() {
            this.checkUser();
            return !(user == null);
        }
    }
}

and app.js smth like that:

app.run(AuthInfo) {
    log(AuthInfo.isLogin());
    if (AuthInfo.isLogin())....
}

the problem is that in console I can see only false. because checkUser() function working async and when isLogin() returns user async request wasn't finish. How can I edit my code to work with it, I need AuthInfo.isLogin() in ng-show and others services and controllers

Pls Go On
  • 51
  • 1
  • 3

1 Answers1

0

checkUser should return the promise, and you have to check the existence of the user in a callback:

Something like that:

function (Api) {
    var user = null;
    return {
        checkUser: function () {
            return Api.checkAuth().then(function (userObj) {
                user = userObj;
            })
        }, 
        isLogin: function() {
            return this.checkUser().then(function () {
                return user !== null;
            });
        }
    }
}

AuthInfo.isLogin().then(...)

Note that there is no point having two methods, you could merge both:

function (Api) {
    return {
        isUserLogged: function () {
            return Api.checkAuth().then(function (userObj) {
                return userObj !== null;
            })
        }
    }
}

AuthInfo.isUserLogged().then(...)
Michel
  • 26,600
  • 6
  • 64
  • 69