Lab 07: Auth Guard
📖 Resources
Section titled “📖 Resources”🚀 Starter Code
Section titled “🚀 Starter Code”step-5-album-wholesale-v16-post-add-custom-async-validator
Continue from your previous lab result. If you need a fresh copy, use step-5-album-wholesale-v16-post-add-custom-async-validator as your base and complete Labs 05 and 06 first.
In this lab, you’ll implement route protection using a functional auth guard. You’ll create a CanActivate guard to restrict access to authenticated users, build a simple authentication service with login logic, and redirect unauthorized users to the login page.
📝 Instructions
Section titled “📝 Instructions”Step 1: Create Auth Guard
Section titled “Step 1: Create Auth Guard”Create a guard to protect routes:
import { inject } from '@angular/core';import { Router, CanActivateFn } from '@angular/router';
export const authGuard: CanActivateFn = (route, state) => { const authService = inject(AuthService); const router = inject(Router);
if (authService.isLoggedIn()) { return true; }
return router.createUrlTree(['/login']);};Step 2: Apply to Routes
Section titled “Step 2: Apply to Routes”Add guard to route configuration:
const routes: Routes = [ { path: 'albums/add', component: AlbumAddComponent, canActivate: [authGuard] }];Step 3: Create Auth Service
Section titled “Step 3: Create Auth Service”Implement authentication logic:
@Injectable({ providedIn: 'root' })export class AuthService { private isAuthenticated = signal(false);
login(username: string, password: string): boolean { if (username === 'admin' && password === 'admin') { this.isAuthenticated.set(true); return true; } return false; }
isLoggedIn(): boolean { return this.isAuthenticated(); }}
