Sub topic 12
Letting features talk without coupling them
This chapter assumes you can write Angular services with inject() and signals. It also assumes you know the feature folders, barrels and route-scoped providers from the earlier chapters. Features rarely stay fully separate. An order page needs the signed-in customer, and a customer page wants to show an order count. A cart badge in the header changes when a product page adds an item. The question is how to allow this traffic without every feature importing every other feature.
What coupling looks like
Suppose customers reaches into the orders feature like this:
import { OrdersStore } from '../orders/data-access/orders.store';This causes three problems:
- It bypasses the orders barrel, so the customers feature now depends on orders internals.
OrdersStoreis provided on the orders route only. Injecting it from a customers component throws aNullInjectorError, because the customers route has no such provider.- Moving or renaming anything in orders now breaks customers.
The goal is a small, explicit contract between features. Dependencies should point downward toward shared layers, not sideways between features.
Five ways to communicate
Pick the lightest option that fits the interaction.
| Option | Use it when | Coupling cost |
|---|---|---|
| URL (route and query params) | One feature links to another and passes an identifier | Very low. Only the URL shape is shared |
| Parent composition (inputs and outputs) | A container renders two features side by side | Low. The parent knows both, the children do not |
| Shared state service in a lower layer | Several features read or write the same data (session, cart) | Medium. Everyone depends on one contract |
| Event bus | A feature announces that something happened, and others may react | Low to medium. Dependencies are on event types |
| Port with an injection token | A feature needs data it does not own, and you want to hide who supplies it | Low. The consumer owns the interface |
The URL is a contract too
The simplest cross-feature message is a link. The customers feature can link to /orders?customerId=42 without importing anything from orders. The orders list reads customerId from the query params. Both features depend only on the URL shape. Route params also survive page reloads and can be bookmarked, which in-memory messages cannot.
Keep such URL shapes in one place if several features use them, for example a small util library of path builders. Otherwise a path rename silently breaks links.
Shared state belongs in a lower layer
If two features need the same data, neither should own it. Move it to a layer both may depend on: core for app-wide concerns, or a data-access library for a domain concept. Unlike OrdersStore, this service is provided in root, because it must be one instance for the whole app.
import { Injectable, computed, signal } from '@angular/core';
export interface CartLine {
productId: string;
quantity: number;
}
@Injectable({ providedIn: 'root' })
export class CartState {
private readonly _lines = signal<CartLine[]>([]);
readonly lines = this._lines.asReadonly();
readonly itemCount = computed(() =>
this._lines().reduce((sum, line) => sum + line.quantity, 0),
);
add(productId: string): void {
this._lines.update((lines) => {
const existing = lines.find((l) => l.productId === productId);
if (existing) {
return lines.map((l) =>
l.productId === productId ? { ...l, quantity: l.quantity + 1 } : l,
);
}
return [...lines, { productId, quantity: 1 }];
});
}
}The product feature calls cart.add(id). The header reads cart.itemCount(). Neither knows the other exists. Expose state as read-only signals and change it only through methods, as in the earlier state chapter. That keeps the contract narrow.
A root-provided service is global state. Use it only for data that really is app-wide. If you put every feature's store in root, you have given up the route scoping you set up earlier.
Events for "something happened"
Shared state suits data that several features read. An event suits a notification where the sender does not care who listens. For example, orders announces that an order was placed, and a notifications feature shows a toast. A small typed bus in core is enough:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';
export type AppEvent =
| { type: 'order-placed'; orderId: string }
| { type: 'customer-deleted'; customerId: string };
@Injectable({ providedIn: 'root' })
export class EventBus {
private readonly events$ = new Subject<AppEvent>();
publish(event: AppEvent): void {
this.events$.next(event);
}
on<T extends AppEvent['type']>(
type: T,
): Observable<Extract<AppEvent, { type: T }>> {
return this.events$.pipe(
filter((e): e is Extract<AppEvent, { type: T }> => e.type === type),
);
}
}A listener subscribes with bus.on('order-placed') and gets a correctly narrowed type. Two gotchas apply:
- A plain
Subjectdoes not replay. A feature that is lazy-loaded after the event fired never sees it. If a late listener needs the current state, use shared state instead. - Subscriptions must end. In a component, pipe through
takeUntilDestroyed()(call it in an injection context, or pass aDestroyRef). Otherwise listeners pile up each time the component is created.
Ports: let the consumer define what it needs
Sometimes the customers feature wants an order count per customer. Importing orders would couple the two. Instead, customers defines the interface it needs and an injection token. Something else supplies the implementation. This is dependency inversion.
// customers/util/order-summary.port.ts
import { InjectionToken } from '@angular/core';
import { Observable } from 'rxjs';
export interface OrderSummaryPort {
countFor(customerId: string): Observable<number>;
}
export const ORDER_SUMMARY = new InjectionToken<OrderSummaryPort>('ORDER_SUMMARY');The orders feature supplies an adapter that fulfills the port:
// orders/data-access/orders-summary.adapter.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, map } from 'rxjs';
import { OrderSummaryPort } from '@app/customers';
@Injectable({ providedIn: 'root' })
export class OrdersSummaryAdapter implements OrderSummaryPort {
private readonly http = inject(HttpClient);
countFor(customerId: string): Observable<number> {
const id = encodeURIComponent(customerId);
return this.http
.get<unknown[]>(`/api/orders?customerId=${id}`)
.pipe(map((orders) => orders.length));
}
}The app shell is the one place allowed to know both features. It connects them:
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { ORDER_SUMMARY } from '@app/customers';
import { OrdersSummaryAdapter } from '@app/orders';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(),
{ provide: ORDER_SUMMARY, useExisting: OrdersSummaryAdapter },
],
};For this to compile, the customers barrel must export OrderSummaryPort and ORDER_SUMMARY, and the orders barrel must export OrdersSummaryAdapter. In this layout orders depends on a type owned by customers, so the arrow points one way only. A customers component injects ORDER_SUMMARY, and tests replace it with a stub in one line. The cost is extra ceremony, so reserve ports for dependencies that you expect to change or that cross a major boundary.
Choosing a style
Work through these questions in order:
- Can the interaction be a link? Use the URL.
- Do both features appear under one parent view? Compose them there with inputs and outputs.
- Is it data that several features read and change? Put a root-provided service in a lower layer.
- Is it a fact others may react to? Publish an event.
- Does one feature need a capability that belongs to another? Define a port.
Guarding the rules
Communication patterns only help if tooling stops people from skipping them. The boundary rules from the previous chapter cover this. A feature should be allowed to depend on ui, data-access and util libraries, not on another feature. With that rule in place, a direct import ... from '@app/orders' inside customers fails the lint step. The developer then has to choose one of the five options above.
Common mistakes
- Providing a shared service in a route's
providersand then injecting it from another feature. The second feature gets an error or its own separate instance, depending on where it is provided. - Putting feature types such as
Orderintocoreso that everyone can use them. This turnscoreinto a dumping ground. Move only genuinely shared concepts, and keep the rest in the owning feature's barrel. - Using the event bus as the default tool. If most of your code goes through it, you cannot see who depends on whom.
- Storing UI-only values, such as which tab is open, in global state. Keep those in the feature.
Exercise
The orders feature provides OrdersStore in its route providers. A component in the customers feature injects OrdersStore to show an order count and fails at runtime with a NullInjectorError. Name two reasons this design is wrong and describe one fix that keeps the features decoupled.
Show answer
First, the store is scoped to the orders route, so the customers route's injector cannot see it. Second, even if it worked, the import would bypass the orders barrel and make customers depend on orders internals. One fix is a port: customers defines an OrderSummaryPort interface and an ORDER_SUMMARY injection token, orders exposes an adapter that implements the port, and the app config binds the token to the adapter with useExisting. Alternatively, move the data to a root-provided state service in a shared data-access layer that both features may depend on.
Exercise
A notifications feature subscribes to bus.on('order-placed') in a component that is created after the user has already placed an order. It never shows the toast for that order. Why, and what should change?
Show answer
The bus uses a plain Subject, which does not replay past values, so a late subscriber misses earlier events. If the component needs to know the current state, such as the latest order, read it from a shared state service backed by a signal. Keep the event only for notifying listeners that are already active.