I'm attempting to validate if a user is logged in or not as soon as they load the page, but the execution order of the code is making this extremely difficult. Here's the code that checks if the user is logged in:
ngOnInit() {
this.authService.authState.subscribe((user) => {
this.user = user;
this.loggedIn = (this.user != null);
this.getUserProfile(user);
console.log(this.loggedIn);
});
console.log(this.loggedIn);
if (this.loggedIn) {
console.log("Don't Redirect")
} else {
console.log("Redirect");
}
}
When running this code, this code block executes first:
console.log(this.loggedIn);
if (this.loggedIn) {
console.log("Don't Redirect")
} else {
console.log("Redirect");
}
Then if the user is logged in this block will execute second:
this.authService.authState.subscribe((user) => {
this.user = user;
this.loggedIn = (this.user != null);
this.getUserProfile(user);
console.log(this.loggedIn);
});
If the user is not logged in then the code in the subscribe does not execute at all, so I'm having trouble working out how I can redirect users away from the page to the login if they are logged out and keep them where they are and get the user profile if they are logged in. Maybe I've just been staring at it for so long now I just can't get my head round it, but either way can anyone help?