Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Create an Angular application with advanced routing guards and preloading strategies.

  1. User

    Create an Angular application with advanced routing guards and preloading strategies.

  2. GLM 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:

    1. 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 with CanActivate, but distinct in function).
      • Resolve: Fetching data before navigation completes.
    2. Preloading Strategies:

      • PreloadAllModules: The standard strategy (preload everything).
      • Custom Strategy: Selective preloading based on route flags (e.g., preload: true) or network conditions.
    3. Structure:

      • A main app module.
      • A few lazy-loaded feature modules (to demonstrate preloading).
      • Services for Auth and Data.

    Plan:

    1. Project Setup: Briefly mention ng new.
    2. Services:
      • AuthService: Mock login/logout.
      • UserService: Mock data for resolver.
    3. 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.
    4. Preloading Strategy:
      • SelectivePreloadingStrategy: Implements PreloadingStrategy. Checks route data for a preload flag.
    5. Routing Configuration:
      • app-routing.module.ts: Define routes, lazy loading, and apply guards/strategy.
    6. Components:
      • HomeComponent: Basic.
      • DashboardComponent: Protected by AuthGuard.
      • AdminComponent: Protected by AdminGuard.
      • FormComponent: Has canDeactivate logic.
      • 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+, CanActivate is often sufficient for lazy-loaded modules, but CanLoad prevents downloading the code entirely if unauthorized. I'll stick to CanActivate for simplicity unless specifically asked, but adding CanLoad makes it more "advanced" in terms of security optimization. I'll implement CanActivate for the logic but mention CanLoad or combine them for the protected module. Actually, standard practice now often just uses CanActivate for lazy routes, but CanLoad saves bandwidth. I'll use CanActivate primarily but add a CanLoad guard 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:

    1. Services & Models
    2. Guards (The core logic)
    3. Preloading Strategy
    4. Routing & App Module
    5. 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 for CanDeactivate) is sometimes easier to read in classes. Actually, PreloadingStrategy must be a class. So I will use class-based guards for consistency across the routing configuration.

    Step-by-Step Implementation Details:

    • AuthService: Needs isLoggedIn boolean and hasPermission string.
    • UnsavedGuard: Needs to cast the component to an interface CanComponentDeactivate.
    • SelectivePreloading: preload(route: Route, load: () => Observable<any>). If route.data && route.data['preload'] then load(), else of(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 use CanActivate, the chunk downloads, but access is blocked. I will include a CanLoad guard 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 AppModule away but makes the routing definition slightly different (no NgModule for lazy loading, just loadComponent or loadChildren with 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 demonstrates PreloadingStrategy very 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 use loadComponent for everything, but PreloadingStrategy works 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, PreloadAllModules still works on loadChildren: () => import(...).then(m => m.routes)? Actually, standard practice is usually canActivate for protection and PreloadingStrategy for 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, but CanDeactivate is cleaner with a class+interface.

    Let's refine the content.

    1. Preloading Strategy: Custom class.
    2. CanDeactivate: Interface + Guard Class.
    3. Resolver: Simple resolver.
    4. CanActivate/CanLoad: Auth checks.

    I will organize the code into file blocks.

    Files:

    1. auth.service.ts (Mock auth)
    2. guards/auth.guard.ts (CanActivate/CanLoad)
    3. guards/deactivate.guard.ts (CanDeactivate)
    4. guards/resolve.guard.ts (Resolve)
    5. strategies/selective-preloading.ts (Custom Preload)
    6. app-routing.module.ts (Configuration)
    7. app.module.ts (Bootstrap)
    8. app.component.ts (Nav)

    This covers all bases. This application demonstrates a production-grade Angular routing setup featuring:

    1. Custom Preloading Strategy: Selectively preload specific data-heavy modules while ignoring others to save bandwidth.
    2. CanActivate Guard: Authentication check to protect routes.
    3. CanActivateChild Guard: Permission check for nested routes (Role-based access).
    4. CanDeactivate Guard: Preventing users from losing unsaved changes in a form.
    5. Resolve Guard: 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-form
    

    2. The Services

    We need mock services to simulate backend behavior.

    src/app/services/auth.service.ts

    import { 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.ts

    import { 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.ts

    import { 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.ts

    import { 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.ts

    import { 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.ts

    import { 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.ts This component implements the CanComponentDeactivate interface.

    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:

    1. SelectivePreloadingStrategy: We injected it into RouterModule.forRoot. Routes marked with data: { preload: true } will load in the background immediately after the app boots, making navigation to them instant.
    2. canActivate: Used on Dashboard to ensure the user is logged in.
    3. resolve: Used on Dashboard to simulate fetching data before the component loads.
    4. canActivateChild: Used on the Admin route. Even if you are logged in as a User, you cannot access Admin or its children (AdminSettings).
    5. canDeactivate: Used on the Contact Form. If the user types text and tries to leave, they get a confirmation dialog.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.