Create an Angular application with advanced routing guards and preloading strategies.
- User
Create an Angular application with advanced routing guards and preloading strategies.
Assistant
The user wants an Angular application that demonstrates "advanced routing guards and preloading strategies."
This is a request for code and structure, not a philosophical musing or a security bypass. The prompt is safe.
However, I need to make sure I provide a comprehensive example. "Advanced" usually implies:
-
Guards:
CanActivate: Standard authentication check.CanActivateChild: Checking permissions for child routes.CanDeactivate: Preventing navigation away from a form with unsaved changes.CanLoad: Preventing lazy loading of a module if the user isn't authorized (often paired withCanActivate, but distinct in function).Resolve: Fetching data before navigation completes.
-
Preloading Strategies:
PreloadAllModules: The standard strategy (preload everything).- Custom Strategy: Selective preloading based on route flags (e.g.,
preload: true) or network conditions.
-
Structure:
- A main app module.
- A few lazy-loaded feature modules (to demonstrate preloading).
- Services for Auth and Data.
Plan:
- Project Setup: Briefly mention
ng new. - Services:
AuthService: Mock login/logout.UserService: Mock data for resolver.
- Guards:
AuthGuard(CanActivate): Checks if logged in.AdminGuard(CanActivateChild): Checks role.UnsavedChangesGuard(CanDeactivate): Checks a generic interface on the component.UserResolver(Resolve): Fetches user data.
- Preloading Strategy:
SelectivePreloadingStrategy: ImplementsPreloadingStrategy. Checks route data for apreloadflag.
- Routing Configuration:
app-routing.module.ts: Define routes, lazy loading, and apply guards/strategy.
- Components:
HomeComponent: Basic.DashboardComponent: Protected by AuthGuard.AdminComponent: Protected by AdminGuard.FormComponent: HascanDeactivatelogic.DetailComponent: Uses Resolver.
Refining the "Advanced" Aspect:
- CanDeactivate is often tricky because it requires the component to implement an interface. I should show that interface.
- CanLoad vs CanActivate: Since Angular v7.1+,
CanActivateis often sufficient for lazy-loaded modules, butCanLoadprevents downloading the code entirely if unauthorized. I'll stick toCanActivatefor simplicity unless specifically asked, but addingCanLoadmakes it more "advanced" in terms of security optimization. I'll implementCanActivatefor the logic but mentionCanLoador combine them for the protected module. Actually, standard practice now often just usesCanActivatefor lazy routes, butCanLoadsaves bandwidth. I'll useCanActivateprimarily but add aCanLoadguard to the admin module to show the difference.
Code Structure: I will provide a single cohesive code block representing the key files, rather than 20 separate file snippets, or I will break it down by logical sections (Services, Guards, Routing, Components).
Let's go with logical sections:
- Services & Models
- Guards (The core logic)
- Preloading Strategy
- Routing & App Module
- Components
Self-Correction/Double Check: Angular moved to functional guards in recent versions (v14+). The prompt asks for an Angular application, implying the latest standards.
- Class-based guards are deprecated/legacy but still work.
- Functional guards (
canActivate: [() => ...]) are the modern way. However, for an educational "Advanced" example, class-based guards are often clearer to separate concerns, but functional guards are the current best practice. I should probably stick to Class-based guards for this specific request because "Strategies" (like PreloadingStrategy) are class-based interfaces, and keeping consistency helps understanding. Also, complex logic (like dependency injection forCanDeactivate) is sometimes easier to read in classes. Actually,PreloadingStrategymust be a class. So I will use class-based guards for consistency across the routing configuration.
Step-by-Step Implementation Details:
- AuthService: Needs
isLoggedInboolean andhasPermissionstring. - UnsavedGuard: Needs to cast the component to an interface
CanComponentDeactivate. - SelectivePreloading:
preload(route: Route, load: () => Observable<any>). Ifroute.data && route.data['preload']thenload(), elseof(null). - Routes:
home(no guard)dashboard(AuthGuard, Preload)admin(AdminGuard, No Preload or selective)form(CanDeactivate)
Let's write the code. I will condense imports to save space but keep it readable.
One specific nuance: CanLoad. If I use
CanLoad, the code chunk isn't downloaded. If I useCanActivate, the chunk downloads, but access is blocked. I will include aCanLoadguard to demonstrate this "Advanced" distinction.Final check on Angular version syntax. Standalone components are the default now. Should I use Standalone? The prompt asks for an "Angular application". Standalone is the modern way (v15+). Using Standalone simplifies the
AppModuleaway but makes the routing definition slightly different (noNgModulefor lazy loading, justloadComponentorloadChildrenwith a routes array). Decision: I will use Standalone Components structure because it is the current standard. However, lazy loading Modules is still common in enterprise apps. I'll stick to NgModules for lazy-loaded features because it demonstratesPreloadingStrategyvery clearly (preloading modules). Mixing Standalone root with Lazy Module features is a very common real-world pattern during migration or large scale apps. Actually, to make it purely modern, I could useloadComponentfor everything, butPreloadingStrategyworks on Routes regardless. Let's stick to NgModules for the lazy-loaded parts to demonstrate the "module" preloading aspect clearly, as that's usually what "Preloading Strategy" refers to in Angular literature.Wait, if I use purely standalone,
PreloadAllModulesstill works onloadChildren: () => import(...).then(m => m.routes)? Actually, standard practice is usuallycanActivatefor protection andPreloadingStrategyfor performance. I will use the Class-based Guard approach within an NgModule context (or a hybrid) as it is the most robust "Enterprise" pattern people look for when asking for "Advanced Routing". Functional guards are great for simple things, butCanDeactivateis cleaner with a class+interface.Let's refine the content.
- Preloading Strategy: Custom class.
- CanDeactivate: Interface + Guard Class.
- Resolver: Simple resolver.
- CanActivate/CanLoad: Auth checks.
I will organize the code into file blocks.
Files:
auth.service.ts(Mock auth)guards/auth.guard.ts(CanActivate/CanLoad)guards/deactivate.guard.ts(CanDeactivate)guards/resolve.guard.ts(Resolve)strategies/selective-preloading.ts(Custom Preload)app-routing.module.ts(Configuration)app.module.ts(Bootstrap)app.component.ts(Nav)
This covers all bases. This application demonstrates a production-grade Angular routing setup featuring:
- Custom Preloading Strategy: Selectively preload specific data-heavy modules while ignoring others to save bandwidth.
CanActivateGuard: Authentication check to protect routes.CanActivateChildGuard: Permission check for nested routes (Role-based access).CanDeactivateGuard: Preventing users from losing unsaved changes in a form.ResolveGuard: Pre-fetching data before the route loads.
1. Project Setup & Dependencies
First, generate the core files:
ng new advanced-routing-demo --routing --module app cd advanced-routing-demo # Generate Services ng g s services/auth ng g s services/data # Generate Guards ng g g guards/auth --functional ng g g guards/permissions --functional ng g g guards/form-dirty --functional ng g g guards/resolve-user --functional # Generate Components ng g c components/home ng g c components/dashboard ng g c components/admin ng g c components/profile ng g c components/contact-form2. The Services
We need mock services to simulate backend behavior.
src/app/services/auth.service.tsimport { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthService { private loggedIn = false; private role: 'ADMIN' | 'USER' = 'USER'; login(role: 'ADMIN' | 'USER' = 'USER'): void { this.loggedIn = true; this.role = role; } logout(): void { this.loggedIn = false; this.role = 'USER'; } isLoggedIn(): boolean { return this.loggedIn; } getRole(): string { return this.role; } }src/app/services/data.service.tsimport { Injectable } from '@angular/core'; import { Observable, of, delay } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataService { // Simulate slow data fetch getUserDetails(): Observable<string> { return of('John Doe - Resolved Data').pipe(delay(1500)); } }3. The Guards
Here we implement the logic to control navigation flow.
src/app/guards/auth.guard.ts(CanActivate)import { inject } from '@angular/core'; import { CanActivateFn, Router } from '@angular/router'; import { AuthService } from '../services/auth.service'; export const authGuard: CanActivateFn = (route, state) => { const authService = inject(AuthService); const router = inject(Router); if (authService.isLoggedIn()) { return true; } // Redirect to home if not logged in return router.parseUrl('/'); };src/app/guards/permissions.guard.ts(CanActivateChild)import { inject } from '@angular/core'; import { CanActivateChildFn, Router } from '@angular/router'; import { AuthService } from '../services/auth.service'; export const permissionsGuard: CanActivateChildFn = (childRoute, state) => { const authService = inject(AuthService); const router = inject(Router); if (authService.getRole() === 'ADMIN') { return true; } alert('Access Denied: Admins only.'); return router.parseUrl('/dashboard'); };src/app/guards/form-dirty.guard.ts(CanDeactivate) This requires an interface for the component.import { Injectable } from '@angular/core'; import { CanDeactivateFn } from '@angular/router'; import { Observable } from 'rxjs'; // Interface for the component implementing this guard export interface CanComponentDeactivate { canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean; } export const formDirtyGuard: CanDeactivateFn<CanComponentDeactivate> = (component) => { // If the component has the method, call it return component.canDeactivate ? component.canDeactivate() : true; };src/app/guards/resolve-user.guard.ts(Resolve)import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; import { DataService } from '../services/data.service'; export const resolveUserGuard: ResolveFn<string> = (route, state) => { return inject(DataService).getUserDetails(); };4. Advanced Preloading Strategy
This strategy allows us to flag specific routes with
data: { preload: true }. Angular will only preload those routes, saving bandwidth for less critical routes.src/app/strategies/selective-preloading.strategy.tsimport { Injectable } from '@angular/core'; import { PreloadingStrategy, Route } from '@angular/router'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class SelectivePreloadingStrategy implements PreloadingStrategy { preload(route: Route, load: () => Observable<any>): Observable<any> { // Check if the route has 'preload: true' in its data object if (route.data && route.data['preload']) { console.log(`Preloading: ${route.path}`); return load(); } else { return of(null); } } }5. Routing Configuration
We wire everything together here.
src/app/app-routing.module.tsimport { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { DashboardComponent } from './components/dashboard/dashboard.component'; import { HomeComponent } from './components/home/home.component'; import { AdminComponent } from './components/admin/admin.component'; import { ContactFormComponent } from './components/contact-form/contact-form.component'; import { ProfileComponent } from './components/profile/profile.component'; // Guards import { authGuard } from './guards/auth.guard'; import { permissionsGuard } from './guards/permissions.guard'; import { formDirtyGuard } from './guards/form-dirty.guard'; import { resolveUserGuard } from './guards/resolve-user.guard'; // Strategy (used in RouterModule.forRoot options) import { SelectivePreloadingStrategy } from './strategies/selective-preloading.strategy'; const routes: Routes = [ { path: '', component: HomeComponent }, // 1. CanActivate & Resolve Example // Route Data 'preload: true' triggers our custom strategy { path: 'dashboard', component: DashboardComponent, canActivate: [authGuard], resolve: { userData: resolveUserGuard }, data: { preload: true } }, // 2. CanActivateChild Example (Nested Routing) // The AdminComponent has a <router-outlet> for children { path: 'admin', component: AdminComponent, canActivate: [authGuard], canActivateChild: [permissionsGuard], children: [ { path: 'settings', component: ProfileComponent }, // Example child { path: '', redirectTo: 'settings', pathMatch: 'full' } ] }, // 3. CanDeactivate Example // This route will be preloaded because of the strategy { path: 'contact', component: ContactFormComponent, canDeactivate: [formDirtyGuard], data: { preload: true } }, { path: '**', redirectTo: '' } ]; @NgModule({ imports: [RouterModule.forRoot(routes, { // Enable the custom preloading strategy preloadingStrategy: SelectivePreloadingStrategy })], exports: [RouterModule] }) export class AppRoutingModule { }6. The Components
src/app/app.component.html(Main Layout)<h1>Angular Routing Demo</h1> <nav> <a routerLink="/">Home</a> | <a routerLink="/dashboard">Dashboard (Protected)</a> | <a routerLink="/admin">Admin (Role: ADMIN)</a> | <a routerLink="/contact">Contact Form</a> </nav> <hr> <button (click)="loginUser()">Log In (User)</button> <button (click)="loginAdmin()">Log In (Admin)</button> <button (click)="logout()">Log Out</button> <hr> <router-outlet></router-outlet>src/app/app.component.tsimport { Component } from '@angular/core'; import { AuthService } from './services/auth.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(public auth: AuthService) {} loginUser() { this.auth.login('USER'); } loginAdmin() { this.auth.login('ADMIN'); } logout() { this.auth.logout(); } }src/app/components/dashboard/dashboard.component.tsimport { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ template: ` <h2>Dashboard</h2> <p>User is logged in.</p> <p><strong>Resolved Data:</strong> {{ data }}</p> ` }) export class DashboardComponent implements OnInit { data: string = ''; constructor(private route: ActivatedRoute) {} ngOnInit() { // Accessing the data resolved by the Resolve Guard this.route.data.subscribe(d => { this.data = d['userData']; }); } }src/app/components/admin/admin.component.ts<!-- Simple wrapper for child routes --> <h2>Admin Panel</h2> <p>Only accessible if you logged in as Admin.</p> <router-outlet></router-outlet>src/app/components/contact-form/contact-form.component.tsThis component implements theCanComponentDeactivateinterface.import { Component } from '@angular/core'; import { CanComponentDeactivate } from 'src/app/guards/form-dirty.guard'; @Component({ template: ` <h2>Contact Form</h2> <p>Try typing something and navigating away.</p> <textarea [(ngModel)]="message" placeholder="Type a message..."></textarea> ` }) export class ContactFormComponent implements CanComponentDeactivate { message = ''; canDeactivate(): boolean { if (this.message) { return confirm('You have unsaved changes. Discard them?'); } return true; } }Summary of Features used:
- SelectivePreloadingStrategy: We injected it into
RouterModule.forRoot. Routes marked withdata: { preload: true }will load in the background immediately after the app boots, making navigation to them instant. canActivate: Used on Dashboard to ensure the user is logged in.resolve: Used on Dashboard to simulate fetching data before the component loads.canActivateChild: Used on the Admin route. Even if you are logged in as a User, you cannot accessAdminor its children (AdminSettings).canDeactivate: Used on the Contact Form. If the user types text and tries to leave, they get a confirmation dialog.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.