Guards
Available guards: https://angular.io/api/router#structures
The class-based implementation of guards has been @deprecated. Functional router guards replace the class-based approach.
// auth.constants.ts
export const authGuard = () => {
const authService = inject(AuthService);
const router = inject(Router);
console.log('AuthGuard called');
return authService.isAuthenticated() ? true : router.navigate(['']);
};
// app.routes.ts
export const routes: Routes = [
{path: '', redirectTo: 'sports', pathMatch: 'full'},
{path: 'sports', loadChildren: () => import('./forms/sports/sports.routes').then(m => m.routes)},
{
path: 'grocery',
canActivate: [authGuard],
loadChildren: () => import('./forms/grocery/grocery.routes').then(m => m.routes)
}
];
canActivatedecides if a route can be accessed. If all guards returntrue, navigation continues. If any guard returnsfalse, navigation is cancelled. If any guard returns aUrlTree, the current navigation is cancelled and a new navigation begins to theUrlTreereturned from the guard.ActivatedRouteSnapshotcontains the information about a route associated with a component loaded in an outlet at a particular moment in time.RouterStateSnapshotrepresents the state of the router at a moment in time.- Here, we simply inject
AuthServiceandRouterinauthGuard. - And we return
trueif user is loggedIn, else we navigate user to blank page.
canActivateand other guards accept array which means we can provide multiple guards to single route.