I have a really weird problem. I have an if statement like the such below:
$rootScope.changeView = function(view){
$location.path(view); // path not hash
};
$rootScope.$on('$routeChangeStart', function (event, next) {
console.log(next.requireLogin + " " + LoginService.getUserLoggedIn());
console.log(next.requireLogin && !LoginService.getUserLoggedIn());
if(next.requireLogin && !LoginService.getUserLoggedIn()) {
console.log("No access to panel: not logged in.");
alert("You need to be logged in as an administrator to see this page!");
event.preventDefault();
$timeout(function () {
$rootScope.changeView("/");
}, 500);
}
});
Where LoginServer.getUserLoggedIn and setUserLoggedIn are this:
this.setUserLoggedIn = function(value){
sessionStorage.userIsLoggedIn = value;
};
this.getUserLoggedIn = function() {
return sessionStorage.userIsLoggedIn;
};
The problem is simple. The If statement is never called, even when next.requireLogin is true and LoginService.getUserLoggedIn() is false. The output in the console is as follows:
true false
false
So apparently "next.requireLogin && !LoginService.getUserLoggedIn()" evaluates to false, yet both are the correct values? If it helps, in the Chrome console the last line with "false" is highlighted purple.
Does anyone know what's wrong?
sessionStorage
stores strings, not booleans. So getUserLoggedIn
returns the string "true"
or "false"
, and all non-empty strings are truthy.
Change getUserLoggedIn
to return a boolean.
this.getUserLoggedIn = function() {
return sessionStorage.userIsLoggedIn == 'true';
};
If you'd used console.log(next.requireLogin, LoginService.getUserLoggedIn())
you would have seen the quotes around the second value, and maybe you'd have realized the problem. When you concatenate, you lose the type information.