Routes are an important feature in Angular applications that prevent users from accessing specific pages without permission. Angular route guards help in controlling navigation under certain conditions, like user authentication and authorization.
Angular route guards are interfaces by which you may control navigation inside an application. They allow the application to prevent users from going to certain routes, from leaving a page, or from even loading some modules lazily.
There are five types of Angular guards, as follows:
A CanActivate guard is commonly used to restrict access to routes based on authentication status.
Step 1: Generate the Guard
ng generate guard auth
Step 2: Implement the CanActivate Interface
Modify the auth.guard.ts file:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
Modify the app-routing.module.ts file:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
A CanDeactivate guard can prompt users before they leave a page with unsaved changes.
Step 1: Create the CanDeactivate Guard
ng generate guard unsaved-changes
Step 2: Implement the CanDeactivate Interface
Modify unsaved-changes.guard.ts:
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable({ providedIn: 'root' })
export class UnsavedChangesGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> | boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
Step 3: Apply the Guard to Routes
Modify app-routing.module.ts:
import { UnsavedChangesGuard } from './unsaved-changes.guard';
const routes: Routes = [
{ path: 'edit-profile', component: EditProfileComponent, canDeactivate: [UnsavedChangesGuard] }
];
Step 4: Implement the CanDeactivate Interface in the Component
Modify edit-profile.component.ts:
import { Component } from '@angular/core';
import { CanComponentDeactivate } from '../unsaved-changes.guard';
import { Observable } from 'rxjs';
@Component({
selector: 'app-edit-profile',
templateUrl: './edit-profile.component.html',
})
export class EditProfileComponent implements CanComponentDeactivate {
unsavedChanges = true;
canDeactivate(): Observable<boolean> | boolean {
return this.unsavedChanges ? confirm('You have unsaved changes. Do you really want to leave?') : true;
}
}
Angular route guards can be a more robust means to protect routes, enhancing user experience by controlling who has access in accordance with their authentication, authorization, and other data conditions. Properly applying CanActivate, CanDeactivate, CanLoad, and many other guards makes sure your application is both safe and structured appropriately.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.