Issue
I have a Logout() function in my authentication Service like this:
export class AuthService {
isAuthenticated = new BehaviorSubject(false);
constructor(private router: Router) { }
Logout()
{
console.log('Logout')
if(this.isAuthenticated.value === true)
{this.isAuthenticated.next(false);}
this.router.navigateByUrl('login')
}
}
that gets called from my side menu where it works just fine.
However if I call it from my app.component.ts like this:
constructor(private auth: AuthService)
{this.auth.isAuthenticated.subscribe((x)=>{
if(this.auth.isAuthenticated.value === false)
{
this.auth.Logout();
}
})}
the function gets called (console.log('logout') works) but I don't get Routed
To test the function I made a Button on my HomePage that sets isAuthenticated to false.
export class HomePage {
constructor(private auth: AuthService) {}
Test()
{
this.auth.isAuthenticated.next(false);
}
}
Logout gets called but doesn't work
-> 'Logout' gets logged in Console but doesn't Route
-> changing the button to call the Logout() function directly works just fine
Test()
{
this.auth.Logout();
}
Calling the same Logout function from the side menu on the same Page just works
fine
I don't get any Error Messages.
What is the reason for the function not working when called from app.component and how can I make it work?
Thanks in advance for any Help.
PS: Iam 100% certain that
- The Logout function is called.
- That the route call is not in the if loop
Bonus Info: isAuthenticated is supposed to be false on Logout(). The if loop checking for a true isAuthenticate and setting it to false is just for security
Stackblitz (is stuck in starting dev server for me however all the code is there)
Solution
Your login appears to be subscribed to isAuthenticated and because according to your Stackblitz you dont check for the state of isAuthenticated and just route to your Homepage on change. So you
- change isAuthenticated to false
- get Routed to your Loginpage
- The Login gets the change and Routes you back to your Homepage
Answered By - Mamba
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.