
Angular AuthGuard of RouteGuard
Angular AuthGuard (RouteGuard)
AuthGuard is an angular route guard used to protect the routes from unauthenticated/unauthorized people. there are two type of guard
1 CanActivate
// user-login.guard.ts
import { inject } from '@angular/core';
import {
ActivatedRouteSnapshot,
Router,
RouterStateSnapshot,
} from '@angular/router';
import { AuthService } from '../services/auth.service';
export const UserLoginGuard = async (
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) => {
const authService = inject(AuthService);
const router = inject(Router);
const isLogin = await authService.isUserLogin();
if (!isLogin) {
router.navigate(['/auth'], { queryParams: { return: state.url } });
return false;
}
return true;
};
2 canDeactivate
export const CanLeaveGuard = (component: {
canLeave: () => boolean | Promise<boolean>;
}) => {
return component.canLeave();
};
Declaer canLeave() in component.ts according to your requirment.
Example: I want to validate test component.So, I am suing canLeave() inside test.component.ts
// test.component.ts
async canLeave() {
const confirm = await this.#alertModalService.confirm(
'Are you sure you want to leave ?'
);
if (confirm) return true;
return false;
}
Usage
// app.routes.ts
import { Route } from '@angular/router';
import { CanLeaveGuard, UserLoginGuard } from './guard/user-login.guard';
export const appRoutes: Route[] = [
{
path: '',
canActivate: [UserLoginGuard],
loadComponent: () =>
import('./welcome/welcome.component').then((v) => v.WelcomeComponent),
},
{
path: 'auth',
loadChildren: () => import('./auth/auth.routes').then((v) => v.AuthRoutes),
},
{
path: 'test',
canActivate: [UserLoginGuard],
canDeactivate: [CanLeaveGuard],
loadComponent: () =>
import('./test/test.component').then((v) => v.TestComponent),
},
];