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)
}
];
canActivate
decides 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 theUrlTree
returned from the guard.ActivatedRouteSnapshot
contains the information about a route associated with a component loaded in an outlet at a particular moment in time.RouterStateSnapshot
represents the state of the router at a moment in time.- Here, we simply inject
AuthService
andRouter
inauthGuard
. - And we return
true
if user is loggedIn, else we navigate user to blank page.
canActivate
and other guards accept array which means we can provide multiple guards to single route.