I have a dashboard page where I implemented a CanDeactivate guard to avoid logged users leaving the page before logging out. It works. But when I push my Logout button, the guard still returns true, but it should return false since there is no user logged. This is my guard:
import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
CanDeactivate,
Router,
RouterStateSnapshot,
} from '@angular/router';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { SnackService } from 'src/app/services/snack.service';
@Injectable({
providedIn: 'root',
})
export class LoggedInAuthGuard implements CanDeactivate<boolean> {
constructor(
private afAuth: AngularFireAuth,
private sb: SnackService,
private router: Router
) {}
async canDeactivate(
component: unknown,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot
): Promise<boolean> {
const user = this.afAuth.authState;
const isLoggedIn = !!user;
if (isLoggedIn) {
console.log(isLoggedIn);
this.sb.logoutError(); // opens a snack to warn users it is necessary to logout
}
console.log(isLoggedIn);
return isLoggedIn;
}
}
And this is my navigation bar component where the Logout button is implemented:
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.scss'],
})
export class NavigationComponent implements OnInit {
isHandset$: Observable<boolean> = this.bp.observe([Breakpoints.Handset]).pipe(
map((result) => result.matches),
shareReplay()
);
constructor(
private bp: BreakpointObserver,
public afAuth: AngularFireAuth,
private router: Router
) {}
ngOnInit(): void {}
logout() {
this.afAuth.signOut();
this.router.navigate(['/login']);
}
}
Thanks a lot for any possible help.