• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / Angular / Auth Guard Example

Auth Guard Example

import { inject } from '@angular/core';
import { CanActivateFn, Router, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = async (
route: ActivatedRouteSnapshot
) => {
const authService = inject(AuthService);
const router = inject(Router);

const isLoggedIn = await authService.getIsLoggedIn();

const isAuthPage =
route.routeConfig?.path === 'login' ||
route.routeConfig?.path === 'registration';

if (isLoggedIn && isAuthPage) {
router.navigate(['/']);
return false;
}

if (!isLoggedIn && !isAuthPage) {
router.navigate(['/login']);
return false;
}

return true;
};

Routing with lazy loading and auth guards

import { Routes } from '@angular/router';
import { authGuard } from './auth/auth.guard';

export const appRoutes: Routes = [
{
path: '',
children: [
{
path: '',
redirectTo: 'cases',
pathMatch: 'full',
},
{
path: 'cases',
canActivate: [authGuard], // Csak bejelentkezett felhasználóknak elérhető
loadComponent: () =>
import('./features/cases/cases.component').then(
(m) => m.CasesComponent
),
},
{
path: 'login',
canActivate: [authGuard], // Ha be vagy jelentkezve, átirányít a főoldalra
loadComponent: () =>
import('./auth/login/login.component').then((m) => m.LoginComponent),
},
{
path: 'registration',
canActivate: [authGuard], // Ha be vagy jelentkezve, átirányít a főoldalra
loadComponent: () =>
import('./auth/registration/registration.component').then(
(m) => m.RegistrationComponent
),
},
{
path: '404',
loadComponent: () =>
import('./core/not-found/not-found.component').then(
(m) => m.NotFoundComponent
),
},
{
path: '**',
redirectTo: '404',
},
],
},
];

Filed Under: Angular

About Gabor Flamich

I'm a web developer and designer based in Budapest, Hungary. In recent years, I've documented hundreds of solutions I came across during development. This site is an archive for useful code snippets on WordPress, Genesis Framework and WooCommerce. If You have any questions related to WordPress development, get in touch!

Primary Sidebar

  • angular.io
© 2026 WP Flames - All Right Reserved