// auth.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class AuthService { private loggedIn = false; isLoggedIn() { return this.loggedIn; } toggle() { this.loggedIn = !this.loggedIn; } } // auth.guard.ts import { CanActivateFn, Router } from '@angular/router'; import { inject } from '@angular/core'; import { AuthService } from './auth.service'; export const authGuard: CanActivateFn = () => { const auth = inject(AuthService); const router = inject(Router); if (auth.isLoggedIn()) { return true; } // Returning a UrlTree redirects instead of allowing the route. return router.createUrlTree(['/login']); }; // app.routes.ts import { Routes } from '@angular/router'; import { DashboardComponent } from './dashboard.component'; import { LoginComponent } from './login.component'; import { authGuard } from './auth.guard'; export const routes: Routes = [ { path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] }, { path: 'login', component: LoginComponent }, ]; // login.component.ts — toggles auth state to test both outcomes import { Component, inject } from '@angular/core'; import { RouterLink } from '@angular/router'; import { AuthService } from './auth.service'; @Component({ selector: 'app-login', standalone: true, imports: [RouterLink], template: `
Logged in: {{ auth.isLoggedIn() }}
Try the dashboard `, }) export class LoginComponent { auth = inject(AuthService); } /* Notes: - authGuard runs before /dashboard activates: if isLoggedIn() is true it returns true (allow), otherwise it returns a UrlTree that redirects to /login. - Toggling the auth state and then clicking "Try the dashboard" demonstrates both outcomes — access granted vs redirected back. - The guard injects services freely (AuthService, Router) because it runs inside Angular's DI context. */