This example shows two guards: AuthGuard blocks access if not logged in, and ConfirmExitGuard asks for confirmation before leaving a form with unsaved changes.
import { Injectable } from '@angular/core';
import { CanActivate, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
export interface CanComponentDeactivate {
canDeactivate: () => boolean | Observable<boolean> | Promise<boolean>;
}
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
isLoggedIn = false; // simulate login status
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
if (this.isLoggedIn) {
return true;
} else {
alert('You must log in to access this page.');
return false;
}
}
}
@Injectable({ providedIn: 'root' })
export class ConfirmExitGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(
component: CanComponentDeactivate
): boolean | Observable<boolean> | Promise<boolean> {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
// Example component implementing canDeactivate
import { Component } from '@angular/core';
@Component({
selector: 'app-form',
template: `<h2>Form Page</h2><button (click)="save()">Save</button>`,
})
export class FormComponent implements CanComponentDeactivate {
saved = false;
save() {
this.saved = true;
alert('Form saved!');
}
canDeactivate(): boolean {
if (!this.saved) {
return confirm('You have unsaved changes. Leave anyway?');
}
return true;
}
}