Route Guard in Angular

In Angular, a route guard is a service that can be associated with a route to control navigation. Route guards are used to protect routes by allowing or blocking navigation based on specific conditions. They play a crucial role in implementing access control, authentication and authorization in Angular applications.

There are several route guards types in Angular, each serving a specific purpose.

CanActivate
Decides whether a route can be activated. Returns "true" if navigation should be allowed or "false" if navigation should be blocked.

CanActivateChild
Similar to "CanActivate", but applied to child routes. Decides whether child routes can be activated.

CanDeactivate
Decides whether a route can be disabled, allowing or blocking exit from a route. It is useful for confirmations or saving data before leaving a page.

CanLoad
Decides whether a module can be loaded. Used to implement lazy loading of modules.

Solve
Performs asynchronous operations before activating a route, typically resolving data that will be needed by the route's components.

Why use Route Guards

Access control
Route guards can be used to check whether a user is allowed to access a certain route or resource.

Authentication
It can be used to check whether a user is authenticated before allowing access to certain routes. This is especially important for protecting restricted areas of the application.

Authorization
Route guards can verify that a user has the appropriate authorizations to access a specific route.

Data Validation
Through guards like "CanDeactivate", you can validate whether it's safe to leave a route by saving changes or requesting user confirmation.

Lazy Loading
The "CanLoad" guard is used to decide whether a module can be loaded based on specific conditions. This is useful for optimizing the loading of modules only when they are needed.

How to Implement a Route Guard

To implement a route guard, you create a class that implements one of the previously mentioned interfaces (for example, "CanActivate") and provides the logic necessary to decide whether navigation should be allowed or blocked.

Here is a basic example of a "CanActivate" route guard.

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

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

   constructor(private router: Router) {}

   canActivate(
     route: ActivatedRouteSnapshot,
     state: RouterStateSnapshot
   ): boolean {
     // logic to check authentication
     const authenticatedUser = true;

     if (authenticatedUser) {
       return true; // allows navigation
     } else {
       this.router.navigate(['/login']);
       return false; // block navigation
     }
   }
}

This "AutenticationGuard" route guard checks whether the user is authenticated. If you are authenticated, browsing is permitted; otherwise the user is redirected to the login page.

After you create the guard, you associate it with a route in the route configuration file ("app-routing.module.ts"), as shown in this example:

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ComponentProtectedComponent } from './component-protected/component-protected.component';
import { AutenticationGuard } from './autentication.guard';

const routes: Routes = [
   { path: 'protected', component: ComponentProtectedComponent, canActivate: [AutenticationGuard] },
   // ... other routes
];

@NgModule({
   imports: [RouterModule.forRoot(routes)],
   exports: [RouterModule]
})
export class AppRoutingModule { }

In the example above, the "AutenticationGuard" guard is associated with the "/protected" route. This means that before activating the "/protected" route, the guard will be triggered to check whether navigation should be allowed.

Route guards are a crucial part of the navigation architecture in Angular, providing precise control over access to different parts of the application. They are essential to guarantee a safe and personalized experience for users.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....