CanActivate Guard In Angular.

The CanActivate guard interface in Angular is used to determine if a route can be activated.

It is typically used to protect routes that require authentication or certain conditions to be met before allowing access.

   


          
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } 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(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree {
    if (this.authService.isLoggedIn()) {
      return true; // Allow access to the route
    } else {
      // Redirect to the login page and return false to prevent access to the route
      this.router.navigate(['/login']);
      return false;
    }
  }
}
       

In this example, the AuthGuard class implements the CanActivate interface. The canActivate method is called by the router to determine if the route can be activated. If the user is logged in (as determined by the isLoggedIn method of the AuthService), the method returns true, allowing access to the route. If the user is not logged in, the method redirects to the login page and returns false, preventing access to the route.

Comments