🅰️ Angular Q39 / 125

Explain route guards and their types.

AI-Powered Answer ✓ Answered

Angular route guards are interfaces that can be implemented by classes to control navigation to or from routes. They provide a powerful way to manage access control, data preloading, and user experience during route transitions.

What are Route Guards?

Route guards are services that implement specific interfaces to decide whether a user can navigate to a route, leave a route, or load a lazy-loaded module. They are crucial for implementing security features like authentication and authorization, ensuring that users only access parts of the application they are permitted to see.

Types of Route Guards

Angular provides several types of route guards, each serving a specific purpose during the routing lifecycle:

CanActivate

This guard determines if a user can activate (navigate to) a specific route. It's commonly used for authentication checks, ensuring that only authenticated users can access certain pages.

CanActivateChild

Similar to CanActivate, but it controls activation of child routes within a parent route. This is useful for applying access control consistently to a group of related routes.

CanDeactivate

This guard determines if a user can deactivate (leave) a route. It's often used to prompt users about unsaved changes before navigating away, preventing accidental data loss.

CanLoad

This guard prevents a lazy-loaded module from being loaded at all. It's ideal for authorization, ensuring that modules containing sensitive features are only loaded for users with appropriate permissions.

Resolve

The Resolve guard is used to pre-fetch data before a route is activated. This ensures that all necessary data is available before the component is rendered, providing a smoother user experience and preventing 'flickering' as data loads asynchronously.

Implementing a Route Guard

To implement a route guard, you create a service that implements one or more of the guard interfaces. The guard's method (e.g., canActivate) must return a boolean, Observable<boolean>, Promise<boolean>, or UrlTree to indicate whether navigation should proceed or be canceled/redirected.

typescript
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';

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

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    // Example: check if user is logged in
    const isAuthenticated = /* your authentication service.isLoggedIn() logic */;

    if (isAuthenticated) {
      return true;
    } else {
      // Redirect to login page or any other unauthorized page
      return this.router.createUrlTree(['/login']);
    }
  }
}

You then register the guard in your route configuration:

typescript
const routes: Routes = [
  {
    path: 'admin',
    component: AdminDashboardComponent,
    canActivate: [AuthGuard] // Apply the guard here
  },
  // ... other routes
];

Conclusion

Angular route guards are essential for building robust and secure applications. By leveraging different guard types, developers can precisely control navigation flow, protect routes, manage user sessions, and enhance the overall user experience by pre-fetching data.