Thuta Learning
Angular
AdvancedWeb DevelopmentIntermediate

Route Guards

AngularLesson 3525 min

What you'll walk away with

  • Explain the core concept and Angular data flow of Route Guards
  • Run the example, predict its state and UI, and test edge and error cases
  • Apply a typed safe pattern in a real project and recognize common pitfalls

Explain it simply

Route Guards, in plain language

Route Guards are used to control access to routes (authentication, authorization).

Problem → Why → Solution

The problem — why this concept matters

Assuming a client guard secures API data creates an authorization vulnerability.

A common mistake

One happy-path result does not prove the feature works; empty, loading, error, and cleanup behavior need explicit tests.

Core concept — understand how it works

A route guard controls navigation UX or redirects, while the server remains the authority for authorization security. Returning a UrlTree or redirect result is clearer than imperatively triggering navigation. Keep authentication, role, unsaved-change, and asynchronous checks focused and avoid redirect loops.

Mental model
  1. URL or navigation
  2. router config and guard
  3. component view

Explain the core concept and Angular data flow of Route Guards

Core syntax or pattern

typescript
// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  
  constructor(private authService: AuthService, private router: Router) {}
  
  canActivate(route: ActivatedRouteSnapshot): boolean {
    if (this.authService.isLoggedIn()) {
      return true;  // Allow access
    }
    
    // Redirect to login
    this.router.navigate(['/login']);
    return false;
  }
}

// app-routing.module.ts
const routes: Routes = [
  { 
    path: 'admin', 
    component: AdminComponent,
    canActivate: [AuthGuard]  // Protected route
  },
  { path: 'login', component: LoginComponent }
];

// Other guards:
// canDeactivate - prevent leaving a page
// canLoad - prevent lazy loading
// canActivateChild - protect child routes

A route guard controls navigation UX or redirects, while the server remains the authority for authorization security. Returning a UrlTree or redirect result is clearer than imperatively triggering navigation. Keep authentication, role, unsaved-change, and asynchronous checks focused and avoid redirect loops.

Read the code step by step

  1. URL or navigation// auth.guard.ts

    Route Guards are used to control access to routes (authentication, authorization).

  2. router config and guard}

    A route guard controls navigation UX or redirects, while the server remains the authority for authorization security. Returning a UrlTree or redirect result is clearer than imperatively triggering navigation. Keep authentication, role, unsaved-change, and asynchronous checks focused and avoid redirect loops.

  3. component view// canActivateChild - protect child routes

    Build a protected admin route and an unsaved-edit route, testing logged-out, forbidden, allowed, cancel, and confirm cases.

Execution flow
  1. URL or navigation
  2. router config and guard
  3. component view

Success

Explain the core concept and Angular data flow of Route Guards

Failure

Assuming a client guard secures API data creates an authorization vulnerability.

Route Guards are used to control access to routes (authentication, authorization).

typescript
// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  
  constructor(private authService: AuthService, private router: Router) {}
  
  canActivate(route: ActivatedRouteSnapshot): boolean {
    if (this.authService.isLoggedIn()) {
      return true;  // Allow access
    }
    
    // Redirect to login
    this.router.navigate(['/login']);
    return false;
  }
}

// app-routing.module.ts
const routes: Routes = [
  { 
    path: 'admin', 
    component: AdminComponent,
    canActivate: [AuthGuard]  // Protected route
  },
  { path: 'login', component: LoginComponent }
];

// Other guards:
// canDeactivate - prevent leaving a page
// canLoad - prevent lazy loading
// canActivateChild - protect child routes
You should see
(If the user isn't logged in, they won't be able to access protected routes)

Real-world usage

How to apply it in a real project

Build a protected admin route and an unsaved-edit route, testing logged-out, forbidden, allowed, cancel, and confirm cases.

Mini challenge

Build it yourself

Rebuild the Route Guards example without copying it. Add two normal states, one edge case, and one failure state, and write the expected UI and state transition before running it.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
typescript
// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  
  constructor(private authService: AuthService, private router: Router) {}
  
  canActivate(route: ActivatedRouteSnapshot): boolean {
    if (this.authService.isLoggedIn()) {
      return true;  // Allow access
    }
    
    // Redirect to login
    this.router.navigate(['/login']);
    return false;
  }
}

// app-routing.module.ts
const routes: Routes = [
  { 
    path: 'admin', 
    component: AdminComponent,
    canActivate: [AuthGuard]  // Protected route
  },
  { path: 'login', component: LoginComponent }
];

// Other guards:
// canDeactivate - prevent leaving a page
// canLoad - prevent lazy loading
// canActivateChild - protect child routes

Expected: Explain the core concept and Angular data flow of Route Guards

Show hint

Build a protected admin route and an unsaved-edit route, testing logged-out, forbidden, allowed, cancel, and confirm cases.

Quick quiz 1 / 3

What best describes the core idea of Route Guards?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • URL or navigation → router config and guard → component view
  • A route guard controls navigation UX or redirects, while the server remains the authority for authorization security. Returning a UrlTree or redirect result is clearer than imperatively triggering navigation. Keep authentication, role, unsaved-change, and asynchronous checks focused and avoid redirect loops.
  • Assuming a client guard secures API data creates an authorization vulnerability.
  • Build a protected admin route and an unsaved-edit route, testing logged-out, forbidden, allowed, cancel, and confirm cases.

Angular — Routing — Angular

Easy traps

  • Assuming a client guard secures API data creates an authorization vulnerability.
  • One happy-path result does not prove the feature works; empty, loading, error, and cleanup behavior need explicit tests.

Hands-on Exercise

Rebuild the Route Guards example without copying it. Add two normal states, one edge case, and one failure state, and write the expected UI and state transition before running it.

You'll know it worked when: (If the user isn't logged in, they won't be able to access protected routes)

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Route Guards | Thuta Learning