I've been drilling into the core routing requirements of the application. Specifically, I'm focusing on scenarios where advanced guards will be crucial. My primary goal is to identify the most suitable guard types to illustrate complex routing logic within the Angular framework. I'm prioritizing clarity and maintainability in the implementation.
Refining Preload Logic
I'm now zeroing in on preloading strategies. My main focus is on demonstrating different approaches: built-in, custom, and network-aware. I'm aiming to showcase their strengths and weaknesses, specifically how they impact the initial load time and user experience. I'll ensure to highlight how custom strategies leverage route data for fine-grained control and how to integrate network-aware checks for optimal performance.
Outlining Route Structures
I'm structuring the routes to demonstrate various practical scenarios. I'm focusing on "Admin," "Dashboard," and "Editor" routes, each utilizing different guards (CanMatch, CanActivate, CanDeactivate) and preloading strategies. My priority is to create clean, maintainable, and easily understandable code that will clearly illustrate each routing approach.
Crafting Guard & Service Logic
I'm currently finalizing the service and guard logic. I've defined the necessary methods for AuthService, and the standalone Angular approach makes for cleaner code. Functional guards are in place for authentication and role-based access. I'm focusing on making a robust, adaptable strategy for preloading. The custom preloading strategy now checks for a preload: true flag in the route data, ensuring optimized loading. I am emphasizing clarity and the use of the simplest solution.
Adding Network Checks
I've incorporated a network constraint check to avoid preloading routes on slow connections like 2G or when the user has enabled "Save Data." I'm updating app.routes.ts with lazy-loaded paths, guards, and data properties. In app.config.ts, I'm registering the new strategy. I'm also preparing dummy components for Admin, Dashboard, Login, and Form. I'm now reviewing everything for clarity and correctness, including adding comments to explain guard usage and ensuring the code is valid. I've switched to functional guards and standalone components for a more modern and concise approach. I'm about ready to generate the final output.
Detailing Test Instructions
I'm focusing now on adding comprehensive explanations for testing. I'm writing detailed instructions, like how to simulate different scenarios by logging out or modifying user roles. I want to make the demonstration easy to understand and use. I'm also ensuring the code examples are readable and correct. I will proceed to the final steps.
This approach demonstrates a modern Angular (v17/v18+) application using Standalone Components, Functional Guards, and a Custom Preloading Strategy.
Prerequisites
Ensure you have Angular CLI installed:
bash
npm install -g @angular/cli
ng new advanced-routing-app --standalone --routing
cd advanced-routing-app
Project Structure & Implementation
We will create:
Auth Service: To manage state.
Guards: CanActivate, CanMatch (replaces CanLoad), CanDeactivate, and Resolve.
Custom Strategy: To preload specific routes only if the network connection is good.
1. Auth Service & Data Interfaces
src/app/core/auth.service.ts
This service mocks authentication and user roles.
typescript
import { Injectable, signal } from '@angular/core';
import { of, delay } from 'rxjs';
export type UserRole = 'USER' | 'ADMIN' | 'GUEST';
@Injectable({ providedIn: 'root' })
export class AuthService {
// Using Signals for reactive state
currentUser = signal<{ name: string; role: UserRole } | null>(null);
constructor() {}
login(role: UserRole = 'USER') {
this.currentUser.set({ name: 'John Doe', role });
}
logout() {
this.currentUser.set(null);
}
isAdmin(): boolean {
return this.currentUser()?.role === 'ADMIN';
}
isAuthenticated(): boolean {
return this.currentUser() !== null;
}
// Mock API call for Resolver
getUserData() {
return of({ preferences: { theme: 'dark', notifications: true } }).pipe(delay(1000));
}
}
2. Advanced Functional Guards
src/app/core/guards.ts
We use functional guards (standard in modern Angular) to protect routes and handle data.
typescript
import { inject } from '@angular/core';
import { CanActivateFn, CanMatchFn, CanDeactivateFn, ResolveFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';
// 1. CanActivate: Check if user is logged in
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isAuthenticated()) {
return true;
} else {
return router.createUrlTree(['/login']);
}
};
// 2. CanMatch: Replaces CanLoad. If false, the feature bundle is NOT downloaded.
// Great for Admin modules.
export const adminGuard: CanMatchFn = (route, segments) => {
const authService = inject(AuthService);
return authService.isAdmin();
};
// 3. CanDeactivate: Prevent leaving if form is dirty
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
export const unsavedChangesGuard: CanDeactivateFn<CanComponentDeactivate> = (component) => {
return component.canDeactivate ? component.canDeactivate() : true;
};
// 4. Resolver: Fetch data before route activates
export const userResolver: ResolveFn<any> = (route, state) => {
const authService = inject(AuthService);
return authService.getUserData();
};
3. Custom Preloading Strategy (Network Aware)
src/app/core/opt-in-preload-strategy.ts
This strategy only preloads routes that have data: { preload: true } AND checks if the user has a good network connection.
typescript
import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class NetworkAwarePreloadStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<any>): Observable<any> {
// 1. Check for route data flag
const shouldPreload = route.data && route.data['preload'] === true;
// 2. Check Network Connection (Experimental Web API)
// Avoid preloading if user has 'save-data' on or slow connection (2g)
const conn = (navigator as any).connection;
const saveMode = conn ? conn.saveData : false;
const effectiveType = conn ? conn.effectiveType : '';
if (shouldPreload && !saveMode && effectiveType !== '2g') {
console.log(`🚀 Preloading: ${route.path}`);
return load();
} else {
return of(null);
}
}
}
4. Components (Standalone)
Create these dummy components to visualize the routing.
src/app/pages/home.component.ts
typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
standalone: true,
template: `<h2>Home Page</h2><p>Publicly accessible.</p>`
})
export class HomeComponent {}
src/app/pages/login.component.ts
typescript
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../core/auth.service';
@Component({
selector: 'app-login',
standalone: true,
template: `
<h2>Login</h2>
<button (click)="login('USER')">Login as User</button>
<button (click)="login('ADMIN')">Login as Admin</button>
`
})
export class LoginComponent {
auth = inject(AuthService);
router = inject(Router);
login(role: 'USER' | 'ADMIN') {
this.auth.login(role);
this.router.navigate(['/dashboard']);
}
}
src/app/pages/dashboard.component.ts
typescript
import { Component, Input } from '@angular/core';
import { JsonPipe } from '@angular/common';
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [JsonPipe],
template: `
<h2>Dashboard</h2>
<p>Resolved Data loaded before component:</p>
<pre>{{ resolvedData | json }}</pre>
`
})
export class DashboardComponent {
// Input binding for router data (New in Angular 16+)
@Input() resolvedData: any;
}
Refresh existing page. You should see dashboard.component chunk load automatically in the background (because of data: { preload: true }).
Now Set throttling to "Slow 3G" or enable "Save-Data" simulation. Refresh. The chunk will not preload.
CanActivate Guard:
Try to access /dashboard via URL bar without logging in. You will be redirected to /login.
CanMatch Guard (Admin):
Login as "User". Try to access /admin in URL. You will stay on the current page (or hit wildcard), and the admin chunk will not download in the network tab.
Login as "Admin". The route works.
Resolve Guard:
Click "Dashboard". Notice a slight 1-second delay before navigation completes. This is the resolver fetching data.
CanDeactivate Guard:
Login, go to "Editor". Type in the box. Try to click "Home". A browser alert will ask you to confirm discarding changes.