Utilize the AuthGuard
concept.
Begin by creating a auth-guard.service.ts file.
import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
canActivate() {
console.log('Checking if user is logged in');
return true;
}
canActivateChild() {
console.log('Checking child route access');
return true;
}
}
Next, integrate this into your routing configuration:
export const appRoutes: Routes = [
{
path: 'dashboard',
children: [
{
path: '',
canActivate: [AuthGuard],
component: DashboardComponent
},
{
path: 'users',
component: DashboardUsersComponent,
canActivateChild: [AuthGuard],
children: [
{
path: '',
component: DashboardUsersHomeComponent
},
{
path: ':username',
component: DashboardUserDetailsComponent,
canDeactivate: [CanDeactivateGuard]
}
]
}
]
}
];
Check out these resources for more information:
Link 1
Link 2
Link 3