Back to course

Route Guards: CanActivate (Authorization)

The Complete Angular Developer: From Zero to Hero

37. Route Guards: CanActivate (Authorization)

Route Guards are interfaces used to control navigation access based on specific conditions (e.g., user logged in, user has admin rights). CanActivate determines if a user can enter a route.

1. Creating the Guard

A guard is an injectable service that implements the CanActivate interface.

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

@Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate {

constructor(private authService: AuthService, private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean { if (this.authService.isLoggedIn()) { return true; // Allow access } else { // Redirect unauthorized users to the login page this.router.navigate(['/login']); return false; // Block access } } }

2. Applying the Guard to a Route

Apply the guard using the canActivate array property in the route configuration.

typescript import { AuthGuard } from './auth.guard'; import { DashboardComponent } from './dashboard/dashboard.component';

const routes: Routes = [ { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] // The guard is checked before the component loads }, { path: 'login', component: LoginComponent } ];

If the AuthGuard.canActivate() method returns true, navigation proceeds. If it returns false, navigation is canceled (and in our example, the user is redirected).