The Angular front end
Standalone components, signals for state, and one strongly typed client per resource. About 400 lines of application code gets us a search screen, a detail view and a create form.
Types that mirror the API
export type OrderStatus =
| 'DRAFT' | 'PLACED' | 'PAID' | 'FULFILLED'
| 'DELIVERED' | 'CANCELLED' | 'REFUNDED';
export interface OrderSummary {
id: number;
reference: string;
status: OrderStatus;
totalAmount: number;
currency: string;
placedAt: string | null;
customerName: string;
}
export interface Order extends OrderSummary {
version: number;
lines: OrderLine[];
nextStates: OrderStatus[]; // the server tells us which buttons to render
metadata: Record<string, unknown>;
}
export interface Page<T> { content: T[]; total: number; page: number; size: number; }
nextStates comes straight from OrderStatus.nextStates() in
chapter 3. The UI renders one button per entry, so the transition rules can never drift
between front end and back end.
The HTTP client
@Injectable({ providedIn: 'root' })
export class OrderService {
private http = inject(HttpClient);
private base = `${environment.apiUrl}/orders`;
search(filter: OrderFilter): Observable<Page<OrderSummary>> {
let params = new HttpParams()
.set('page', filter.page)
.set('size', filter.size);
if (filter.status) params = params.set('status', filter.status);
if (filter.text) params = params.set('text', filter.text);
if (filter.from) params = params.set('from', filter.from);
return this.http.get<Page<OrderSummary>>(this.base, { params });
}
get(id: number): Observable<Order> {
return this.http.get<Order>(`${this.base}/${id}`);
}
create(body: CreateOrderRequest): Observable<Order> {
return this.http.post<Order>(this.base, body);
}
transition(id: number, target: OrderStatus, version: number): Observable<Order> {
return this.http.post<Order>(`${this.base}/${id}/transitions`, { target, version });
}
}
Interceptors: token in, errors out
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
const router = inject(Router);
const token = auth.token();
const request = token
? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
: req;
return next(request).pipe(
catchError((err: HttpErrorResponse) => {
if (err.status === 401) {
auth.logout();
router.navigate(['/login'], { queryParams: { returnUrl: router.url } });
}
return throwError(() => err);
})
);
};
export interface ProblemDetail {
title: string; status: number; detail?: string;
errors?: { field: string; message: string }[];
allowed?: string[];
}
export function messageFrom(err: HttpErrorResponse): string {
const p = err.error as ProblemDetail | undefined;
if (!p?.title) return 'Something went wrong. Please try again.';
if (p.errors?.length) {
return p.errors.map(e => `${e.field}: ${e.message}`).join('\n');
}
return p.detail ?? p.title;
}
Because the API returns a consistent error shape, the whole front end needs one function to display any failure — including the validation errors and the 409 conflicts from chapter 3.
A signal store for the list screen
@Injectable({ providedIn: 'root' })
export class OrderStore {
private api = inject(OrderService);
readonly filter = signal<OrderFilter>({ page: 0, size: 20 });
readonly loading = signal(false);
readonly error = signal<string | null>(null);
readonly page = signal<Page<OrderSummary> | null>(null);
readonly orders = computed(() => this.page()?.content ?? []);
readonly total = computed(() => this.page()?.total ?? 0);
readonly totalPages = computed(() =>
Math.ceil(this.total() / this.filter().size));
readonly isEmpty = computed(() =>
!this.loading() && this.orders().length === 0);
constructor() {
// debounce so typing in the search box does not fire a request per keystroke
toObservable(this.filter).pipe(
debounceTime(250),
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
tap(() => { this.loading.set(true); this.error.set(null); }),
switchMap(f => this.api.search(f).pipe(
catchError(err => { this.error.set(messageFrom(err)); return of(null); })
)),
takeUntilDestroyed()
).subscribe(page => {
if (page) this.page.set(page);
this.loading.set(false);
});
}
patchFilter(patch: Partial<OrderFilter>): void {
// any filter change resets to page 0 — otherwise you land on an empty page 7
this.filter.update(f => ({ ...f, ...patch, page: patch.page ?? 0 }));
}
}
switchMap, not mergeMap
Typing "ord" fires three requests. With mergeMap they race and the slowest
wins, so the list can show results for "or" after results for "ord".
switchMap cancels the previous request. This is the single most common
search-box bug in Angular applications.
The list component
@Component({
selector: 'oms-order-list',
standalone: true,
imports: [RouterLink, CurrencyPipe, DatePipe, FormsModule, StatusChipComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<header class="toolbar">
<h1>Orders <small>{{ store.total() }}</small></h1>
<input type="search" placeholder="Reference or customer"
[ngModel]="store.filter().text"
(ngModelChange)="store.patchFilter({ text: $event })">
<select [ngModel]="store.filter().status"
(ngModelChange)="store.patchFilter({ status: $event })">
<option [ngValue]="undefined">All statuses</option>
@for (s of statuses; track s) { <option [ngValue]="s">{{ s }}</option> }
</select>
<a routerLink="/orders/new" class="btn">New order</a>
</header>
@if (store.error(); as error) {
<p class="alert" role="alert">{{ error }}</p>
}
<table>
<tbody>
@for (o of store.orders(); track o.id) {
<tr>
<td><a [routerLink]="['/orders', o.id]">{{ o.reference }}</a></td>
<td>{{ o.customerName }}</td>
<td><oms-status-chip [status]="o.status" /></td>
<td class="num">{{ o.totalAmount | currency:o.currency }}</td>
<td>{{ o.placedAt | date:'medium' }}</td>
</tr>
} @empty {
<tr><td colspan="5">No orders match these filters.</td></tr>
}
</tbody>
</table>
<oms-paginator [page]="store.filter().page" [totalPages]="store.totalPages()"
(goto)="store.patchFilter({ page: $event })" />
`
})
export class OrderListComponent {
protected store = inject(OrderStore);
protected statuses: OrderStatus[] =
['DRAFT','PLACED','PAID','FULFILLED','DELIVERED','CANCELLED','REFUNDED'];
}
track o.id is not optionalWithout a stable track expression Angular destroys and rebuilds every row on each response. With it, a page refresh touches only the rows that actually changed.
Detail and transitions
@Component({ /* … */ template: `
@if (order(); as o) {
<h1>{{ o.reference }} <oms-status-chip [status]="o.status" /></h1>
<div class="actions">
@for (next of o.nextStates; track next) {
<button type="button" [disabled]="busy()" (click)="move(o, next)">
{{ next | transitionLabel }}
</button>
}
</div>
<table>
@for (l of o.lines; track l.id) {
<tr>
<td>{{ l.productName }}</td>
<td class="num">{{ l.quantity }}</td>
<td class="num">{{ l.lineTotal | currency:o.currency }}</td>
</tr>
}
</table>
}
`})
export class OrderDetailComponent {
private api = inject(OrderService);
private id = injectParam('id');
readonly order = signal<Order | null>(null);
readonly busy = signal(false);
move(order: Order, target: OrderStatus): void {
this.busy.set(true);
this.api.transition(order.id, target, order.version).subscribe({
next: updated => { this.order.set(updated); this.busy.set(false); },
error: (err: HttpErrorResponse) => {
this.busy.set(false);
if (err.status === 409) {
// somebody else changed it — reload rather than guess
this.toast.warn(messageFrom(err));
this.reload();
} else {
this.toast.error(messageFrom(err));
}
}
});
}
}
That 409 branch is the visible end of the optimistic-locking chain that started with a
version column in chapter 1.
The create form
export class OrderFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
customerId: this.fb.control<number | null>(null, Validators.required),
lines: this.fb.array([this.newLine()], Validators.required)
});
get lines(): FormArray { return this.form.controls.lines; }
private newLine() {
return this.fb.group({
productId: this.fb.control<number | null>(null, Validators.required),
quantity: this.fb.control(1, [Validators.required, Validators.min(1)])
});
}
addLine() { this.lines.push(this.newLine()); }
removeLine(i: number) { if (this.lines.length > 1) this.lines.removeAt(i); }
// live total, recomputed from the form's value stream
readonly total = toSignal(
this.form.valueChanges.pipe(
startWith(this.form.value),
map(v => (v.lines ?? []).reduce((sum, l) =>
sum + (this.priceOf(l.productId) * (l.quantity ?? 0)), 0))
), { initialValue: 0 });
submit(): void {
if (this.form.invalid) { this.form.markAllAsTouched(); return; }
this.api.create(this.form.getRawValue() as CreateOrderRequest).subscribe({
next: o => this.router.navigate(['/orders', o.id]),
error: (err: HttpErrorResponse) => this.applyServerErrors(err)
});
}
// map ProblemDetail field errors back onto the matching controls
private applyServerErrors(err: HttpErrorResponse): void {
for (const e of (err.error as ProblemDetail).errors ?? []) {
this.form.get(e.field.replace(/\[(\d+)\]/g, '.$1'))
?.setErrors({ server: e.message });
}
}
}
The client-side figure is for feedback while typing. The server recalculates from the
catalogue in OrderService.create and that value wins — otherwise a modified
request could set its own prices.
Routes and guards
export const routes: Routes = [
{ path: 'login', loadComponent: () =>
import('./features/auth/login.component').then(m => m.LoginComponent) },
{
path: 'orders',
canActivate: [authGuard],
loadChildren: () => import('./features/orders/orders.routes')
.then(m => m.ORDER_ROUTES)
},
{
path: 'admin',
canActivate: [authGuard, roleGuard(['ADMIN'])],
loadChildren: () => import('./features/admin/admin.routes')
.then(m => m.ADMIN_ROUTES)
},
{ path: '', redirectTo: 'orders', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent }
];
export const roleGuard = (allowed: string[]): CanActivateFn => () => {
const auth = inject(AuthService);
return allowed.some(r => auth.roles().includes(r))
|| inject(Router).createUrlTree(['/forbidden']);
};
roleGuard keeps a viewer from landing on a screen full of buttons they cannot
use. The actual enforcement is @PreAuthorize from
chapter 4. Lazy loading also means a viewer never downloads
the admin bundle.
What we have built
- A schema whose constraints make invalid orders impossible.
- MyBatis mappers that load the aggregate in one query and page without OFFSET.
- A service with an explicit state machine, optimistic locking and an outbox.
- A REST API with typed errors and a tested authorisation matrix.
- An Angular client with signals, lazy routes and server-driven actions.
It runs on your machine. The next course puts it in a container and then in the cloud.
Why does the order payload include nextStates instead of the UI computing them?
Duplicating the state machine in TypeScript guarantees the two copies diverge the first time a rule changes. Sending the allowed transitions makes the server authoritative and the client trivial.