0

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.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Luiz Federico
  • 21
  • 1
  • 4
  • `const isLoggedIn = !!user` is `true` when `user` is of any truthy value. Make sure `user` actually points to a a falsy value when you log the user out (aka `null` or `undefined`) –  Mar 15 '22 at 14:57
  • You probably also want to return `!isLoggedIn` - when the user is logged out, the can deactivate guard should return `true` –  Mar 15 '22 at 15:00

0 Answers0