Home > Blockchain >  Logout function doesnt work when called from app.component.ts
Logout function doesnt work when called from app.component.ts

Time:01-12

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

  1. The Logout function is called.
  2. 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)

CodePudding user response:

I think it is routing related issue and please check where you define the route.

CodePudding user response:

I ended up continuing to work on my Project when all the sudden it worked here is the change that helped:

Function where i get from login to home Page:

  async onSubmit() //original
  {
    this.auth.Login(this.loginForm.value.name, this.loginForm.value.password).subscribe((res)=>
    {
      if(true)
      {
        this.Route()
      }
})

  async onSubmit() //new
  {
    this.auth.Login(this.loginForm.value.name, this.loginForm.value.password).subscribe((res)=>
    {
      if(res)
      {
        this.Route()
      }
})

Can someone explain why this stopped the Route from Working?

  • Related