Sub topic 2
Lazy-loading features with the router
Assume you know TypeScript, standalone Angular components, dependency injection, and the Angular Router. This chapter shows how to load a feature on demand, give it feature-scoped state, and expose only its intended public API.
Lazy-loading features with the router
A lazy-loaded feature is downloaded when the user first navigates to it. The application-level route maps a URL prefix to the feature's route file. loadComponent then loads individual standalone components.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'orders',
loadChildren: () =>
import('./orders/orders.routes').then((m) => m.ORDERS_ROUTES),
},
];The feature owns its route details:
import { Routes } from '@angular/router';
import { OrdersStore } from './data-access/orders.store';
export const ORDERS_ROUTES: Routes = [
{
path: '',
providers: [OrdersStore],
children: [
{
path: '',
loadComponent: () =>
import('./feature/order-list.component').then(
(m) => m.OrderListComponent,
),
},
{
path: ':id',
loadComponent: () =>
import('./feature/order-detail.component').then(
(m) => m.OrderDetailComponent,
),
},
],
},
];Scoping services to a feature route
The providers array on the route creates OrdersStore in that route's injector. Components under the route can inject it, while unrelated features cannot use that instance accidentally.
Keeping feature state inside the feature
The store has no root provider. It keeps mutable state private and exposes a read-only signal, which is an Angular value that updates consumers when its value changes.
import { Injectable, computed, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class OrdersStore {
private readonly http = inject(HttpClient);
private readonly _orders = signal<string[]>([]);
readonly orders = this._orders.asReadonly();
readonly count = computed(() => this._orders().length);
load(): void {
this.http
.get<string[]>('/api/orders')
.subscribe((orders) => this._orders.set(orders));
}
}A common error is placing feature state in a global store before another feature needs it. Keep state local until there is a clear cross-feature requirement.
Defining a feature's public API with a barrel
A barrel file is an index that re-exports the symbols other code may use.
// src/app/orders/index.ts
export { ORDERS_ROUTES } from './orders.routes';
export type { Order } from './data-access/order.model';Import the feature through a path alias such as @app/orders, rather than reaching into its private folders. This makes internal file moves safer and documents the feature boundary.
Exercise
Where should a service go when only the orders route and its child components need one shared instance?
Show answer
Provide it in the orders route's providers array, and declare the service with @Injectable() without providedIn: 'root'.