I encountered an issue with redirection when a user is not logged in. In my project, I have two Guards for the Admin and User roles. I am using functions from the @angular/fire/auth-guard library to handle redirection based on the login status. However, when I add my custom guards along with the built-in ones, the guard that checks if a user is logged in or not stops working properly and causes the page to keep loading indefinitely. Here's an example of the code:
In the code snippet below, both RolUserGuard and RoleAdminGuard are functioning correctly, but the AuthGuards for home and admin components are causing the pages to load endlessly without redirecting to the login page. On the other hand, when a logged-in user tries to access the login page, the AuthGuard works as expected.
const redirectUnauthorizedToLogin = () => redirectUnauthorizedTo(['']);
const redirectLoggedInToHome = () => redirectLoggedInTo(['home']);
const routes : Routes = [
{path : '',redirectTo: 'login', pathMatch: 'full'},
{path : 'login', component : LoginComponent, canActivate: [AuthGuard], data: {authGuardPipe: redirectLoggedInToHome}},
{path : 'home', component : HomeComponent, canActivate: [AuthGuard,RoleUserGuard], data: {authGuardPipe: redirectUnauthorizedToLogin} },
{path : 'admin', component : AdminComponent, canActivate: [AuthGuard,RoleAdminGuard], data: {authGuardPipe: redirectUnauthorizedToLogin}, children:[
{path : '', component : AdminUsersComponent},
{path : 'user/:id', component: DetailsComponent}
]},
{path : '**', component: PageNotFoundComponent}
]
Could there be an error in my implementation? Is it possible that the issue lies with the data property, causing conflicts when multiple Guards are added? Any insights would be appreciated.
Below is the code snippet for the other guards, which follows a similar structure with minor differences:
canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const rol = localStorage.getItem('rolUser');
if(rol!=='admin'){
this.router.navigate(['/home']);
return false;
}
return true;
}