My current struggle lies within the authentication guard logic and routing setup.
In my app-routing.module.ts file, I have defined 3 routes:
const routes: Routes = [
{
path: '',
loadChildren: () => import('./browse/browse.module').then(m => m.BrowseModule),
},
{
path: AppRoutes.auth,
loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
},
{
path: AppRoutes.landing,
loadChildren: () => import('./landing/landing.module').then(m => m.LandingModule),
},
];
One of these paths leads to the ''
route which sends users to the BrowseModule
at /browser
.
Within the browser-routing.module.ts
, I've implemented an AuthGuard
that redirects users to the landing
page if they are not authenticated:
const routes: Routes = [
{
path: '',
component: BrowseComponent,
redirectTo: BrowseRoutes.browse,
},
{
path: BrowseRoutes.browse,
loadChildren: () => import('./home/home.module').then(m => m.HomeModule),
canActivate: [AuthGuard]
}
];
AuthGuard.ts :
canActivate(
route: ActivatedRouteSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.hasToken()) {
if(this.authService.isAuthenticated()){
console.log('logged in guard');
this.router.navigate(['browse']);
return true;
} else {
console.log('not logged in guard');
this.router.navigate(['landing']);
return false;
}
} else {
console.log('no token not logged in guard');
this.router.navigate(['landing']);
return false;
}
}
The issue at hand is :
When I am logged in, there seems to be an infinite loop occurring with the AuthGuard
. It continuously prints either "not logged in" and cycles between "/
" and "/browse
", or it shows "logged in" and enters an infinite loop once more. How can this be resolved?