Skip to main content

canActivate guard in angular | Angular 19

A Guard is a type of service used to control navigation and manage access to routes in an application. Guards help protect routes by implementing logic to determine whether a route can be activated, deactivated, loaded, or unloaded.

Types of Guards in Angular

CanActivate: Prevents unauthorized users from accessing specific routes.

CanActivateChild: Controls access to child routes.

CanDeactivate: Prevents users from leaving a route when specific conditions are not met.

Resolve: Fetches data before navigating to a route, ensuring the required data is available.

CanLoad: Prevents loading of feature modules unless the user has permission.

How to Implement Guards

1. Generate a Guard

You can create a guard using the Angular CLI: ng generate guard auth

2. Implement a Guard

Here's an example of an AuthGuard using CanActivate: 

auth.guard.ts

export const authGuard: CanActivateFn = (route, state) => {
debugger;
  const router = inject(Router) // It is arrow function show we declare variable
  const loggedUser = localStorage.getItem("loginToken")

  if(loggedUser != null){
    return true;
  }else{
    router.navigateByUrl('login')
    return false;
  }
};

  • Guards improve route security and user experience.
  • Combine multiple guards in the canActivate or other guard arrays for complex logic.
3. Protect a Route with the Guard

app.routes.ts

export const routes: Routes = [
    {
        path:'login',
        component:LoginComponent
    },
    {
        path:'',
        redirectTo:'login',
        pathMatch:'full'
    },
    {
        path:'',
        component:LayoutComponent,
        children:[
          {  
            path:'dashboard',
            component:DashboardComponent,
            canActivate: [authGuard] //Authontication when user login then redirect to layout
          }
        ]
    },
    {
      path:'**',   //WildCart Route
      component:LoginComponent
    }

];


More details GithubRepo

Comments

© 2020 The JavaDS Hub

Designed by Open Themes & Nahuatl.mx.