Course Progress 98%

Angular Route Guards

Angular Route Guards routing security और navigation control का सबसे important mechanism हैं। Guards decide करते हैं कि user किसी route को access कर सकता है या नहीं, route से बाहर जा सकता है या किसी module को load करने की permission है या नहीं। Large और secure Angular applications में guards almost हर जगह use होते हैं।

इस chapter में हम Angular Route Guards को beginner से advanced level तक detail में समझेंगे, with clear concepts और practical examples।

Route Guards क्या होते हैं

Route Guards Angular Router के special services होते हैं जो navigation lifecycle के दौरान execute होते हैं और boolean या UrlTree return करके navigation allow या block करते हैं।

Guards use होते हैं:

  • Authentication check
  • Authorization (role-based access)
  • Unsaved changes protection
  • Lazy module protection

Angular Guards के Types

Angular में main guards होते हैं:

  • CanActivate
  • CanActivateChild
  • CanDeactivate
  • CanLoad
  • Resolve

हर guard का purpose अलग होता है।

CanActivate Guard

CanActivate decide करता है कि route activate होगा या नहीं।

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return this.isLoggedIn();
  }
}

Route configuration:

{
  path: 'dashboard',
  component: DashboardComponent,
  canActivate: [AuthGuard]
}

False return करने पर navigation block हो जाती है।

Redirecting from Guard

Unauthorized user को login page पर redirect किया जा सकता है।

canActivate(): boolean | UrlTree {
  return this.isLoggedIn()
    ? true
    : this.router.createUrlTree(['/login']);
}

UrlTree navigation-friendly redirection provide करता है।

CanActivateChild Guard

Child routes को protect करने के लिए:

{
  path: 'admin',
  canActivateChild: [AdminGuard],
  children: [
    { path: 'users', component: UsersComponent },
    { path: 'settings', component: SettingsComponent }
  ]
}

Parent guard child routes पर apply होता है।

CanDeactivate Guard

User को route छोड़ने से रोकने के लिए use होता है।

Example: unsaved form protection

export interface CanExit {
  canExit: () => boolean;
}
export class UnsavedGuard implements CanDeactivate<CanExit> {
  canDeactivate(component: CanExit): boolean {
    return component.canExit();
  }
}

Component:

canExit() {
  return confirm('Unsaved changes will be lost');
}

CanLoad Guard

Lazy-loaded module load होने से पहले check करता है।

{
  path: 'admin',
  canLoad: [AuthGuard],
  loadChildren: () =>
    import('./admin/admin.module').then(m => m.AdminModule)
}

Unauthorized user के लिए module download ही नहीं होगा।

CanLoad vs CanActivate

  • CanLoad: module loading रोकता है
  • CanActivate: navigation रोकता है

Sensitive modules के लिए CanLoad ज्यादा secure होता है।

Resolve Guard

Resolve guard route activate होने से पहले data fetch करता है।

@Injectable({ providedIn: 'root' })
export class UserResolver implements Resolve<User> {
  resolve(): Observable<User> {
    return this.service.getUser();
  }
}

Route:

{
  path: 'profile',
  component: ProfileComponent,
  resolve: { user: UserResolver }
}

Accessing Resolved Data

this.route.snapshot.data['user'];

Component load होते ही data available होता है।

Async Guards

Guards Observable या Promise return कर सकते हैं।

canActivate(): Observable<boolean> {
  return this.authService.isLoggedIn$;
}

Angular router async guard completion का wait करता है।

Multiple Guards per Route

canActivate: [AuthGuard, RoleGuard]

Guards sequentially execute होते हैं।

Guard Execution Order

Typical order:

  • CanLoad
  • CanActivate
  • CanActivateChild
  • Resolve

Understanding order debugging में help करता है।

Standalone Guards

Modern Angular functional guards support करता है।

export const authGuard: CanActivateFn = () => {
  return inject(AuthService).isLoggedIn();
};

Route:

canActivate: [authGuard]

यह lightweight और future-ready approach है।

Guards और Route Parameters

Guards parameters access कर सकते हैं।

canActivate(route: ActivatedRouteSnapshot) {
  const id = route.paramMap.get('id');
}

यह validation और permission checks में useful है।

Common Guard Mistakes

  • Heavy logic guards में डालना
  • API calls unnecessarily repeat करना
  • canLoad और canActivate confuse करना
  • Redirect loops create करना

Guards lightweight और focused होने चाहिए।

Real-World Guard Scenarios

Angular Route Guards widely use होते हैं:

  • Login-protected dashboards
  • Role-based admin panels
  • Unsaved form warnings
  • Feature toggles

Angular Route Guards application routing को secure और controlled बनाते हैं। अगले और final routing chapter में हम Angular Router Advanced cover करेंगे, जहाँ advanced navigation patterns, resolvers, reuse strategies और performance optimizations detail में सीखेंगे।