Table of Contents
Angular’s Router Guards are a powerful feature that help developers control access to different parts of an application. They act as gatekeepers, ensuring that only authorized users can navigate to certain routes. This is especially useful for protecting sensitive pages such as user profiles, admin dashboards, or payment sections.
What Are Angular Router Guards?
Router Guards are services that implement specific interfaces to determine if a route can be activated, deactivated, loaded, or if the user can access a route based on certain conditions. Angular provides several built-in guards, including CanActivate, CanDeactivate, CanLoad, and Resolve.
Common Types of Guards
- CanActivate: Checks if a route can be entered.
- CanDeactivate: Checks if a route can be exited.
- CanLoad: Checks if a module can be loaded lazily.
- Resolve: Pre-fetches data before route activation.
Implementing a Guard with CanActivate
To protect a route, you typically implement the CanActivate interface in a service. Here’s a simple example:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isAuthenticated = /* your authentication logic */;
if (isAuthenticated) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
Applying Guards to Routes
After creating the guard, apply it to your routes in the routing module:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ProtectedComponent } from './protected/protected.component';
import { AuthGuard } from './guards/auth.guard';
const routes: Routes = [
{
path: 'protected',
component: ProtectedComponent,
canActivate: [AuthGuard]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
Using Router Guards effectively enhances the security of your Angular application by controlling access based on user roles, authentication status, or other custom conditions. Proper implementation ensures a safer, more controlled user experience.