I'm having issues with Angular routing that don't seem to make much sense. With the following set-up, this outcome occurs...
- App loads at path
/
- Auth guard runs
- Auth guard returns false as there is not yet a JWT in storage
- Redirection to
/login
works as expected.
However...
- Navigate directly to
/activate
(Route in the account module) - Console logs that the auth guard is being run (Which shouldn't happen)
- Redirected to
/login
I'm struggling to understand why auth guard is running for the /activate
route when it's not a child of the dashboard layout.
App routes
{
path: '',
component: DashboardLayoutComponent,
canActivate: [AuthGuard],
canActivateChild: [DashboardGuard],
children: [
{
path: 'schedule',
loadChildren: () =>
import('@libs/schedule').then(
i => i.ScheduleModule
),
data: {
breadcrumb: 'Schedule'
}
},
// Other feature modules omitted
{
path: '',
redirectTo: '/schedule',
pathMatch: 'full'
}
]
}
Account Routes
{ path: 'login', component: LoginComponent },
{ path: 'activate', component: ActivateComponent }
Auth Guard
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private jwtService: JwtService,
private router: Router,
private accountService: accountService
) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
console.log('Auth Guard Start'); // <-- This appears in console
return this.jwtService.getToken().pipe(
map(token => {
if (!token) {
this.router.navigate(['/login']);
return false;
}
// Attempt to populate the user using the token.
this.accountService.populate();
return true;
}),
take(1)
);
}
}
App Module
@NgModule({
declarations: [AppComponent, DashboardLayoutComponent],
imports: [
// .. other modules omitted
AccountModule,
AppRoutingModule
],
providers: [AuthGuard, DashboardGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
Additional information
This happens when running in production mode only.
Augury reports that /login
and /activate
are both siblings of the /
route. https://i.stack.imgur.com/2LDY4.jpg
@angular/core: 8.2.6
@angular/router: 8.2.6