skip to Main Content

I’m trying to write a simple guard for my application. My auth system is based on firebase, with the possibility to login with Google.
This is my guard code:

import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const AuthGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService)
  console.log("Guard state: ", authService.user)

  if(!authService.isLoggedIn()){
    inject(Router).navigate(['login'])
  }

  return authService.isLoggedIn()
}

The authService.isLoggedIn() method just returns the value of auth.currentUser.

Now, if I call this function, let’s say, in my app-component with a (click) event, everything works fine, but inside the guard I always get a false.
I suspect the problem is with the service injection, maybe a new instance of the AuthService is created every time, losing all my reference to the actual authentication situation.
Any idea?

2

Answers


  1. Chosen as BEST ANSWER

    I solved it by creating a new Promise inside of my authService. The Promise is resolved or rejected inside the onAuthStateChanged() so I can just make async the canActivate method and wait for the auth state to be updated.


  2. You can directly use

    import { AuthGuard, redirectUnauthorizedTo } from '@angular/fire/auth-guard';
    const unauthRedirect = () => redirectUnauthorizedTo(['/signin']);
    
    export const routes: Routes = [{
        path: 'account',
        component: AccountComponent,
        canActivate: [AuthGuard],
        data: { authGuardPipe: unauthRedirect }
    },
    ... 
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search