0
0
AngularHow-ToBeginner · 4 min read

How to Use Route Guard in Angular: Simple Guide

In Angular, use CanActivate route guards to control access to routes by implementing the CanActivate interface in a service and adding it to your route's canActivate array. This lets you check conditions like user login before allowing navigation.
📐

Syntax

A route guard in Angular is a service that implements the CanActivate interface. You create a method canActivate() that returns true or false (or an Observable/Promise of these) to allow or block route access. Then, you add this guard service to the route's canActivate array in your routing module.

  • Guard Service: Implements CanActivate interface.
  • canActivate(): Returns boolean or Observable/Promise.
  • Route config: Add guard to canActivate array.
typescript
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    // Your logic here
    return true; // or false to block
  }
}

// In your routing module
const routes = [
  {
    path: 'protected',
    component: ProtectedComponent,
    canActivate: [AuthGuard]
  }
];
💻

Example

This example shows a simple AuthGuard that allows access only if the user is logged in. The guard checks a fake AuthService and blocks navigation if not logged in.

typescript
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthService {
  isLoggedIn = false;
  login() { this.isLoggedIn = true; }
  logout() { this.isLoggedIn = false; }
}

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (this.authService.isLoggedIn) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

// Routing module snippet
const routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent }
];
Output
If user is logged in, navigating to '/dashboard' shows DashboardComponent; otherwise, user is redirected to '/login'.
⚠️

Common Pitfalls

  • Forgetting to provide the guard service in root or module providers causes injection errors.
  • Not returning a boolean or Observable/Promise from canActivate leads to unexpected behavior.
  • Not adding the guard to the route's canActivate array means the guard won't run.
  • Redirecting inside canActivate without returning false can cause navigation loops.
typescript
/* Wrong: Missing return in canActivate */
canActivate() {
  if (this.authService.isLoggedIn) {
    return true;
  }
  this.router.navigate(['/login']);
  // Missing return false here causes issues
  return false;
}

/* Right: Always return boolean */
canActivate() {
  if (this.authService.isLoggedIn) {
    return true;
  }
  this.router.navigate(['/login']);
  return false;
}
📊

Quick Reference

Route Guard Cheat Sheet:

  • CanActivate: Blocks or allows route activation.
  • canActivate(): Method to implement guard logic.
  • canActivate: [YourGuard]: Add guard to route config.
  • Return true to allow, false to block navigation.
  • Use Router to redirect if needed.

Key Takeaways

Implement the CanActivate interface in a service to create a route guard.
Add your guard service to the route's canActivate array to protect routes.
Return true to allow navigation or false to block it, optionally redirecting users.
Always provide your guard service and return a boolean or Observable/Promise.
Test guards by simulating conditions like user login to ensure correct route access.