I have a routing setup with 3 specific routes:
const routes: Routes = [
{
path: '',
component: DashboardComponent,
canActivate: [AuthGuard],
children: [
{path: 'products', component: ProductsListComponent},
{path: 'orders', component: OrdersListComponent}
]
}
];
@NgModule({
imports: [
RouterModule.forChild(routes)
],
exports: [
RouterModule
]
})
export class DashboardRoutingModule {
}
However, the AuthGuard
currently only protects the child routes, products
and orders
. It is essential to also protect the root route /
.
UPDATE 1 for AuthGuard
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private authService: AuthService, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.isLoggedIn) {
return true;
} else {
this.router.navigate(['/login'], {
queryParams: {
accessDenied: true
}
});
return false;
}
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.canActivate(childRoute, state);
}
}
And here is the AuthService
:
@Injectable()
export class AuthService {
private loggedIn = false;
get isLoggedIn() {
return this.loggedIn;
}
constructor(private router: Router) {
}
login(user: User) {
this.loggedIn = true;
window.localStorage.setItem('user', JSON.stringify(user));
this.router.navigate(['/products']);
}
logout() {
this.loggedIn = false;
window.localStorage.clear();
this.router.navigate(['/login']);
}
}