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
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.You can directly use