Sub topic 3
Lazy Loading, Guards, Resolvers, and Beyond
This chapter assumes you already know the route configuration, RouterOutlet, RouterLink, and Router.navigate from the earlier chapters. You should also be comfortable with inject() and RxJS operators.
Lazy Loading Components and Route Groups
To lazy load a route, you point it at a dynamic import() instead of a component class. The bundler then splits that code into a separate chunk. Use loadComponent for one standalone component and loadChildren for a whole Routes array.
import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
import { productResolver } from './product.resolver';
export const routes: Routes = [
{
path: 'settings',
loadComponent: () => import('./settings.component').then(m => m.SettingsComponent)
},
{
path: 'admin',
canActivate: [authGuard],
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
},
{
path: 'products/:id',
loadComponent: () => import('./product-detail.component').then(m => m.ProductDetailComponent),
resolve: { product: productResolver }
}
];Protecting Routes with Functional Guards
A guard is a function that returns true, false, or a UrlTree that redirects the user. It can also return that value inside an Observable or a Promise.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = () =>
inject(AuthService).isLoggedIn() ? true : inject(Router).createUrlTree(['/login']);CanActivateFn runs after the lazy chunk downloads. CanMatchFn runs during route matching, so if it fails, the chunk is never fetched and the router goes on to try the next route. CanDeactivateFn runs when the user tries to leave a route, which makes it useful for warning about unsaved changes.
Loading Data Before Navigation with Resolvers
A ResolveFn fetches data before the route activates. The result is stored in route.data under the key you chose. If you enabled withComponentInputBinding(), the router also passes it to a matching input, here @Input() product.
Observing Navigation with Router Events
Router.events emits NavigationStart, NavigationEnd, NavigationError, and other event types. Filter the stream for the events you need:
import { Component, inject } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
@Component({ selector: 'app-tracker', standalone: true, template: '' })
export class TrackerComponent {
constructor() {
inject(Router).events
.pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd))
.subscribe(e => console.log('Visited', e.urlAfterRedirects));
}
}Path vs Hash Location Strategies
| Strategy | URL | Server requirement |
|---|---|---|
| Path (default) | `/products/42` | Must return `index.html` for every app URL |
| Hash (`withHashLocation()`) | `/#/products/42` | None |
Preloading Lazy Routes
provideRouter(routes, withPreloading(PreloadAllModules)) downloads lazy chunks in the background after the first navigation. Routes protected by canMatch are skipped until their guard passes.
Testing Routed Components
RouterTestingHarness lets a test run real navigations against your routes:
import { TestBed } from '@angular/core/testing';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { ProductDetailComponent } from './product-detail.component';
it('renders the product id', async () => {
TestBed.configureTestingModule({
providers: [provideRouter(
[{ path: 'products/:id', component: ProductDetailComponent }],
withComponentInputBinding()
)]
});
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/products/42');
expect(harness.routeNativeElement?.textContent).toContain('Product 42');
});Exercise
Users who are not admins should never download the admin chunk. Which guard type should protect the lazy admin route, and why?
Show answer
Use canMatch. It runs before the lazy chunk loads, so if it fails, nothing is downloaded. canActivate runs only after the chunk has already been fetched.