What is authguard and use of canActivate?

CanActivate is an interface in the Angular Router module that provides a way to control access to specific routes in an Angular application. The interface has a single method canActivate that you can implement to decide whether the user should be allowed to navigate to the requested route or not.

An Auth Guard is a type of service in Angular that implements the CanActivate interface and is used to control access to specific routes based on the authentication status of the user. For example, you could use an Auth Guard to restrict access to routes that require authentication, or to redirect the user to a login page if they are not logged in.

Here’s an example of a basic Auth Guard implementation:

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

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

  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      
    let isLoggedIn = this.checkLogin();

    if (!isLoggedIn) {
      this.router.navigate(['/login']);
      return false;
    }

    return true;
  }

  checkLogin(): boolean {
    // Here you would typically check if the user is logged in by checking a
    // value in local storage, making a request to a server, etc.
    return false;
  }
}

In this example, the AuthGuard checks the user’s authentication status by calling the checkLogin method. If the user is not logged in, the guard redirects them to the login page by calling the router.navigate method. If the user is logged in, the guard allows access to the requested route by returning true.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *