Reputation: 1335
In my application I try to make a simple login screen with a guard for a lazy loaded module, so the module won't load if no token exists in the local storage, and if no token exists it should redirect me to a login component. The problem I encountered is that the guard triggers ad infinitum, the browser eventually crashing, and I don't get it why this happens.
Here is my code:
const routes: Routes = [
{
path: '',
redirectTo: 'main',
pathMatch: 'full',
},
{ path: '**', redirectTo: 'main' },
{
path: 'main',
loadChildren: () => MainScreenModule,
canLoad: [AuthGuard],
},
{
path: 'login',
component: LoginScreenComponent,
},
];
export const AppRouting: ModuleWithProviders = RouterModule.forRoot(routes);
Module that should be loaded routing:
const routes: Routes = [
{
path: '',
component: MainRoomScreenComponent,
},
];
export const MainScreenRouting: ModuleWithProviders = RouterModule.forChild(routes);
The guard:
@Injectable()
export class AuthGuard implements CanLoad {
constructor(private router: Router) {}
canLoad(route: Route) {
if (localStorage.getItem('access_token')) {
console.log('Token found');
return true;
} else {
console.log('No authorization found');
this.router.navigate(['/login']);
return false;
}
}
}
In the guard code, the 2nd console log, the one with No authorization will print forever in the console. I don't get what is wrong, since by my logic it is the follow: I load the program (with either an empty path, main or some path that doesn't exist, the program redirects to 'main', the guard activates and checks if the token exists, if yes it proceeds with main, else it doesn't load main and redirects to login. What am I doing wrong?
Upvotes: 0
Views: 237
Reputation: 725
const routes: Routes = [
{
path: '',
redirectTo: 'main',
pathMatch: 'full',
},
{
path: 'main',
loadChildren: () => MainScreenModule,
canLoad: [AuthGuard],
},
{
path: 'login',
component: LoginScreenComponent,
},
{ path: '**', redirectTo: 'main' }
];
path: '**' means match everything / any route. So when you're redirecting to /login
route but ** is before the /login route so again going into the loop.
Upvotes: 1
Reputation: 1272
Do not put canLoad: [AuthGuard] to your lazy loading module this is example
this is main.routing.ts
const routes: Routes = [
{
path: 'general',
loadChildren: () => import('../modules/application/application.module').then(m =>
m.ApplicationModule)
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
this is general.routing.ts
const routes: Routes = [
{
path: 'info/:applicationFormId',
component: GeneralInfoComponent,
canActivate: [TokenGuard]
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
Upvotes: 0