Providing example Angular app with custom matcher and CanLoad guard
Here is a full Angular setup illustrating an advanced router using a custom UrlMatcher for product-{id}, a CanLoad guard checking JWT permissions asynchronously to prevent lazy chunk downloads, and disabling preloading to respect CanLoad behavior. The example includes main routing, AuthService, PermissionsGuard, and a lazy-loaded ProductModule with a product detail route.
Below is a minimal Angular setup that demonstrates:
- A custom
UrlMatcher that matches URLs like product-123 (i.e., product-{id}).
- A lazy‐loaded module for product details, whose chunk is only downloaded if the
CanLoad guard grants access.
- A
CanLoad guard that checks JWT permissions asynchronously and returns false if the user lacks permission, preventing the lazy module from loading.
Important: Avoid preloading strategies that bypass CanLoad (e.g., PreloadAllModules). If you must use preloading, implement a custom preloading strategy that respects canLoad.
1) App Routing with Custom UrlMatcher and Lazy Load
app-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule, UrlSegment, UrlMatchResult } from '@angular/router';
import { PermissionsGuard } from './guards/permissions.guard';
import { HomeComponent } from './home/home.component';
// Custom matcher for "product-{id}" URLs
export function productMatcher(url: UrlSegment[]): UrlMatchResult | null {
if (!url.length) return null;
const path = url[0].path;
const match = path.match(/^product-(\d+)$/);
if (match) {
// capture "id" from the regex group
const posParams = { id: new UrlSegment(match[1], {}) };
return { consumed: [url[0]], posParams };
}
return null;
}
const routes: Routes = [
{ path: '', component: HomeComponent },
{
// Match product-123 etc. via custom matcher
matcher: productMatcher,
canLoad: [PermissionsGuard],
loadChildren: () =>
import('./product/product.module').then((m) => m.ProductModule),
},
// Fallback
{ path: '**', redirectTo: '' },
];
@NgModule({
imports: [
RouterModule.forRoot(routes, {
// Keep preloading off if you rely on canLoad to block chunk download
// preloadingStrategy: NoPreloading // default anyway
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
2) CanLoad Guard Checking JWT Permissions Asynchronously
permissions.guard.ts:
import { Injectable } from '@angular/core';
import { CanLoad, Route, UrlSegment, Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { catchError, map, tap } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class PermissionsGuard implements CanLoad {
constructor(private authService: AuthService, private router: Router) {}
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> {
// Example: we require a permission "canViewProducts"
const neededPermission = 'canViewProducts';
return this.authService.getPermissionsFromToken().pipe(
map((permissions) => permissions.includes(neededPermission)),
tap((allowed) => {
if (!allowed) {
// Redirect or show error page
this.router.navigate(['/']);
}
}),
catchError((err) => {
// On error, treat as not allowed
this.router.navigate(['/']);
return of(false);
})
);
}
}
How it works:
canLoad returns an Observable<boolean>.
- It decodes or verifies JWT in
AuthService.getPermissionsFromToken().
- If permission is missing, returns
false; the lazy module chunk will not be downloaded.
3) Auth Service Example (JWT Permissions)
auth.service.ts:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
// You can use a real JWT library like @auth0/angular-jwt or jose
@Injectable({ providedIn: 'root' })
export class AuthService {
private tokenKey = 'my_jwt';
// Replace with your real JWT parsing/verification
getPermissionsFromToken(): Observable<string[]> {
const token = localStorage.getItem(this.tokenKey) || '';
// Dummy implementation: parse token or call API to validate permissions
// In real code, decode and verify the token, then extract claims/permissions
const decodedPermissions = this.fakeDecodePermissions(token);
return of(decodedPermissions);
}
// Stub for example
private fakeDecodePermissions(token: string): string[] {
// Example logic: if token includes "admin", grant all; else none
if (token.includes('admin')) return ['canViewProducts', 'canEditProducts'];
return ['canViewProducts']; // or [] to test blocked access
}
}
Replace this with actual JWT verification/decoding as needed.
4) Lazy‐Loaded Product Module
product/product-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProductComponent } from './product.component';
const routes: Routes = [
{
path: '',
component: ProductComponent,
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class ProductRoutingModule {}
product/product.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProductRoutingModule } from './product-routing.module';
import { ProductComponent } from './product.component';
@NgModule({
declarations: [ProductComponent],
imports: [CommonModule, ProductRoutingModule],
})
export class ProductModule {}
product/product.component.ts:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product',
template: `
<h2>Product detail</h2>
<div>Product ID: {{ productId }}</div>
`,
})
export class ProductComponent implements OnInit {
productId: string | null = null;
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
// Because we used UrlMatcher, the param is named "id"
this.productId = this.route.snapshot.paramMap.get('id');
}
}
5) App Module and Home Component
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
@NgModule({
declarations: [AppComponent, HomeComponent],
imports: [BrowserModule, AppRoutingModule],
bootstrap: [AppComponent],
})
export class AppModule {}
home.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
template: `
<h1>Welcome</h1>
<p>Try navigating to /product-123.</p>
`,
})
export class HomeComponent {}
6) Usage
- Ensure you do not use a preloading strategy that ignores
CanLoad (the default is NoPreloading).
- Set a JWT in
localStorage to simulate permissions:
// In browser console for example
localStorage.setItem('my_jwt', 'admin-token');
// or:
localStorage.setItem('my_jwt', 'user-token');
- Navigate to
/product-123.
- If the guard deems you have
canViewProducts, it will load the ProductModule lazily and show the detail.
- Otherwise, it won’t download the lazy chunk and will redirect to
/.
This setup demonstrates a custom regex‐based UrlMatcher and an async CanLoad guard to keep unauthorized users from loading lazy modules.