State or events: two reactive models
A signal exposes its current value synchronously through its getter. Angular records dependencies read in a reactive context; computed evaluates lazily, caches its result and tracks only dependencies actually read. Updating a signal does not synchronously render the DOM. [1]
An Observable can emit zero, one or many values, synchronously or asynchronously, and can complete or fail. It need not expose a current value. A regular Observable may start separate work for each subscriber; a Subject can multicast events. A BehaviorSubject requires an initial value and gives an active new subscriber the current value. Do not replace an event log with a single signal. [2][3] [15]
Component state and derived values
The search feature holds text in a signal and derives the trimmed query in computed. There is no need for another writable signal synchronized by an effect. Once a list is available, local filtering, result counts and selection state can often be derived instead of synchronized. [1][4]
Signals use Object.is equality by default. Mutating an array in place may fail to trigger the expected update; create a new reference for changes. asReadonly prevents set and update through that reference but does not freeze the object. In an OnPush template Angular tracks signal reads and marks the component for an update. Do not assume a performance advantage: measure computation cost, request counts and rendering time. [1]
Choosing a model and sharing data
Signals fit form state, filters and derived calculations; Observables fit events, WebSocket messages, concurrent work and time-based policies. A Subject is useful for commands whose individual occurrences must not collapse into state, such as successive save clicks. linkedSignal holds writable dependent state, for example a product selection that should be reconsidered when its list changes. Avoid copying one signal into another through effect. [1][4][18]
HttpClient returns a cold Observable: two independent subscriptions generally initiate two requests. Share results deliberately, for example using shareReplay({ bufferSize: 1, refCount: true }); refCount disconnects a still-active source when the last subscriber leaves, but does not provide automatic TTL or invalidation of a completed response. Do not build a global private-data cache without separating user contexts. [5][19]
Search state and HTTP data contracts
Related reading: JavaScript Promises and async/await.
search-model.ts
export interface Product {
readonly id: string;
readonly name: string;
}
export type SearchState =
| { kind: "idle"; query: string }
| { kind: "loading"; query: string }
| { kind: "success"; query: string; items: readonly Product[] }
| { kind: "error"; query: string };
export const MIN_QUERY_LENGTH = 2;
export const SEARCH_DELAY_MS = 300;
export function normalizeQuery(query: string): string {
return query.trim();
}
export function canSearch(query: string): boolean {
return query.length >= MIN_QUERY_LENGTH;
}
export function pendingState(query: string): SearchState {
if (!canSearch(query)) {
return { kind: "idle", query };
}
return { kind: "loading", query };
}
export function visibleState(
query: string,
state: SearchState,
): SearchState {
if (query !== state.query) {
return pendingState(query);
}
return state;
}
products.ts
import type { Product } from "./search-model";
function isRecord(value: unknown): value is Record<string, unknown> {
if (value === null) {
return false;
}
if (Array.isArray(value)) {
return false;
}
return typeof value === "object";
}
function isNonEmptyString(value: unknown): value is string {
if (typeof value !== "string") {
return false;
}
return value.trim().length > 0;
}
function parseProduct(value: unknown): Product {
if (!isRecord(value)) {
throw new TypeError("Expected a product object.");
}
const { id, name } = value;
if (!isNonEmptyString(id)) {
throw new TypeError("Invalid product ID.");
}
if (!isNonEmptyString(name)) {
throw new TypeError("Invalid product name.");
}
return { id, name };
}
export function parseProducts(value: unknown): readonly Product[] {
if (!Array.isArray(value)) {
throw new TypeError("Expected an array of products.");
}
const records: unknown[] = value;
const products = records.map(parseProduct);
const ids = new Set(products.map((product) => product.id));
if (ids.size !== products.length) {
throw new TypeError("Duplicate product IDs.");
}
return products;
}
The demo requires two characters after trimming. Its 300 ms delay and minimum length are design choices, not UX standards. A discriminated union distinguishes idle, loading, success and error, so an empty result is not presented as a failure. Each state includes the query that produced it.
HttpClient.get<unknown> makes response validation explicit. A generic type argument does not validate JSON. The parser accepts arrays of records with non-empty string id and name fields, rejecting duplicate identifiers used by track. Separate structure and value checks with guard clauses. In a real application add a backend contract, response limits and localized error messages. [5]
Resilient transport and stream contract
products-api.ts
import type { HttpClient } from "@angular/common/http";
import { map } from "rxjs";
import type { Observable } from "rxjs";
import { parseProducts } from "./products";
import type { Product } from "./search-model";
export const SEARCH_URL = "/api/products";
export const REQUEST_TIMEOUT_MS = 10_000;
export function loadProducts(
http: HttpClient,
query: string,
): Observable<readonly Product[]> {
return http
.get<unknown>(SEARCH_URL, {
params: { q: query },
timeout: REQUEST_TIMEOUT_MS,
})
.pipe(map(parseProducts));
}
The loadProducts adapter separates HTTP transport from the component and limits backend waiting to 10 seconds. This is an example policy, not a universal value; HttpClient's timeout does not include delays introduced by interceptors or the 300 ms delay before the request. [5]
The search contract expects one response per query. first() takes the first value and raises an error if the source completes without emitting; otherwise the view could remain loading. An empty array is a valid response, not an error. Unsubscription through switchMap is not an error and should not display a failure message. [20]
RxJS and concurrency policies
Related reading: JavaScript Debounce vs Throttle.
search-stream.ts
import {
catchError,
concat,
defer,
distinctUntilChanged,
first,
map,
of,
switchMap,
timer,
} from "rxjs";
import type { Observable } from "rxjs";
import {
canSearch,
normalizeQuery,
pendingState,
SEARCH_DELAY_MS,
} from "./search-model";
import type { Product, SearchState } from "./search-model";
export type LoadProducts = (
query: string,
) => Observable<readonly Product[]>;
function searchQuery(
query: string,
load: LoadProducts,
): Observable<SearchState> {
if (!canSearch(query)) {
return of(pendingState(query));
}
const response$ = timer(SEARCH_DELAY_MS).pipe(
switchMap(() => defer(() => load(query))),
first(),
map((items): SearchState => ({ kind: "success", query, items })),
catchError(() => of<SearchState>({ kind: "error", query })),
);
return concat(of(pendingState(query)), response$);
}
export function createSearchState(
queries$: Observable<string>,
load: LoadProducts,
): Observable<SearchState> {
return queries$.pipe(
map(normalizeQuery),
distinctUntilChanged(),
switchMap((query) => searchQuery(query, load)),
);
}
Related reading: Long Tasks, Main Thread and INP.
Latest-wins search uses switchMap. When a new normalized query is emitted, the previous inner subscription, including its timer or active HTTP request, is disposed. The timer sits inside switchMap: placing debounceTime before it would allow an older request to finish while a new emission is pending. distinctUntilChanged ignores consecutive identical normalized values. [3][6][7]
concatMap queues operations, mergeMap permits concurrency (which can be bounded), and exhaustMap ignores new emissions during an active operation. Choose by semantics rather than operator speed. Do not use switchMap for writes without examining consequences. Unsubscribing from HTTP aborts client-side work, but does not guarantee reversal of server-side work. [3][5]
Converting between signals and Observables
toSignal subscribes at creation time. Call it once at a component boundary, not inside a getter, computed or template. Supply initialValue or handle undefined. requireSync is appropriate only for sources guaranteed to emit synchronously on subscription; a normal HTTP stream is not such a source. Completion retains the last value, while an unhandled error is thrown when the signal is read. [8]
toObservable uses an effect and emits stabilized state; multiple consecutive writes may produce a single emission. It is not a click log. The demo's computed visibleState also hides results for an old query during the brief interval before emission. catchError within each query stream maps failure to an error state, so subsequent distinct queries remain possible. Both conversions normally need an injection context or a supplied Injector. [8] [17]
Component, template and lifetime
search.component.ts
import { HttpClient } from "@angular/common/http";
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
signal,
} from "@angular/core";
import { toObservable, toSignal } from "@angular/core/rxjs-interop";
import { loadProducts } from "./products-api";
import {
MIN_QUERY_LENGTH,
normalizeQuery,
visibleState,
} from "./search-model";
import type { SearchState } from "./search-model";
import { createSearchState } from "./search-stream";
const INITIAL_STATE: SearchState = { kind: "idle", query: "" };
@Component({
selector: "app-search",
standalone: true,
templateUrl: "./search.component.html",
styleUrl: "./search.component.css",
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SearchComponent {
private readonly http = inject(HttpClient);
protected readonly minQueryLength = MIN_QUERY_LENGTH;
protected readonly query = signal("");
private readonly normalized = computed(() =>
normalizeQuery(this.query()),
);
private readonly result = toSignal(
createSearchState(
toObservable(this.normalized),
(query) => loadProducts(this.http, query),
),
{ initialValue: INITIAL_STATE },
);
protected readonly state = computed(() =>
visibleState(this.normalized(), this.result()),
);
protected updateQuery(query: string): void {
this.query.set(query);
}
}
search.component.html
<section class="search-panel" aria-labelledby="search-heading">
<h1 id="search-heading">Product search</h1>
<label for="product-query">Product name</label>
<input
#queryInput
id="product-query"
type="search"
[value]="query()"
(input)="updateQuery(queryInput.value)"
/>
@let current = state();
<div role="status" aria-live="polite">
@switch (current.kind) {
@case ("idle") {
<p>Enter at least {{ minQueryLength }} characters.</p>
}
@case ("loading") {
<p>Searching…</p>
}
@case ("success") {
<p>{{ current.items.length }} results.</p>
}
@case ("error") {
<p>Search failed. Change your query to try again.</p>
}
}
</div>
@if (current.kind === "success") {
<ul class="search-results">
@for (product of current.items; track product.id) {
<li>{{ product.name }}</li>
}
</ul>
}
</section>
search.component.css
.search-panel {
display: grid;
gap: 1rem;
max-width: 36rem;
margin-inline: auto;
padding: 1rem;
}
.search-panel input {
box-sizing: border-box;
width: 100%;
padding: 0.75rem;
font: inherit;
}
.search-results {
margin: 0;
padding-inline-start: 1.5rem;
}
main.ts
import { provideHttpClient } from "@angular/common/http";
import { bootstrapApplication } from "@angular/platform-browser";
import { SearchComponent } from "./search.component";
bootstrapApplication(SearchComponent, {
providers: [provideHttpClient()],
}).catch((error: unknown) => {
console.error("Application bootstrap failed.", error);
});
Place the files in one standalone component directory. The entry point configures HttpClient; /api/products is a sample contract for your own backend. The template uses @let, @switch, @for, a semantic input label and a status message. Angular's (input) is a framework event binding, not a native inline oninput attribute. CSS lives in a separate file.
The result signal is created in the component lifetime, so toSignal normally unsubscribes when the component is destroyed. For a manual subscription, use AsyncPipe for template consumption or takeUntilDestroyed (pass DestroyRef explicitly outside an injection context); place teardown downstream of operators that create inner subscriptions. Reserve effect for external synchronization, with onCleanup for resources; use computed for derivations. [4][8][9] [16]
Resource APIs and incremental migration
Angular 22 marks resource, httpResource and rxResource stable. Earlier versions had different labels and may expose different APIs. resource ties parameters to an asynchronous read; httpResource exposes HTTP status and response as signals and initiates requests without manual subscription. rxResource accepts an Observable source. Consider these abstractions for straightforward resource reads. [10][11][12]
Do not treat resource as a safe mutation mechanism: changing parameters or destruction can abort a load. For writes choose explicit commands with conflict, idempotency and error handling. If an existing service has a sound Observable contract, retain it and convert at the view boundary. Do not rewrite an entire project just because Signals are available. [10]
Alternative: httpResource on form submission
product-resource.ts
import { httpResource } from "@angular/common/http";
import { signal } from "@angular/core";
import { parseProducts } from "./products";
import { REQUEST_TIMEOUT_MS, SEARCH_URL } from "./products-api";
import { canSearch, normalizeQuery } from "./search-model";
// Call once in an Angular injection context, e.g. a field initializer.
export function createProductResource() {
const query = signal("");
const products = httpResource(
() => {
const current = query();
if (!canSearch(current)) {
return undefined;
}
return {
url: SEARCH_URL,
params: { q: current },
timeout: REQUEST_TIMEOUT_MS,
};
},
{ parse: parseProducts },
);
function submit(rawQuery: string): void {
query.set(normalizeQuery(rawQuery));
}
function retry(): void {
if (!canSearch(query())) {
return;
}
products.reload();
}
return { products, submit, retry };
}
When a request should follow form submission rather than each keystroke, the following httpResource factory is an option. Create it once in an injection context, such as a component field initializer. Pass text to submit when the form is submitted, not on every input. Returning undefined from the request function prevents loading for short queries. The parse option reuses the same parser. [11][21]
Check error(), isLoading() and hasValue() before reading value(); reading the value in an error state may throw. retry uses reload(), which need not start another request when a resource is already loading. During reloading the previous value may remain available. This alternative does not implement the 300 ms delay or the earlier full template; retain RxJS for complex timing and event policies. [21][22]
Angular 22 also provides experimental debounced from @angular/core. During the wait its resource can still expose the previous settled value. Connecting debounced to resource therefore does not by itself guarantee cancellation on every keystroke. Check the API status and semantics before adopting it; the main example retains stable RxJS. [24]
Tests and acceptance criteria
search-stream.spec.ts
import { describe, expect, it } from "vitest";
import { TestScheduler } from "rxjs/testing";
import type { Product, SearchState } from "./search-model";
import { createSearchState } from "./search-stream";
function createScheduler(): TestScheduler {
return new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
}
describe("search state", () => {
it("cancels an active request on a newer query", () => {
createScheduler().run((helpers) => {
const { cold, hot, expectObservable, expectSubscriptions } = helpers;
// Given
const first = cold<readonly Product[]>("500ms a|", {
a: [{ id: "1", name: "Old" }],
});
const items = [{ id: "2", name: "New" }];
const second = cold<readonly Product[]>("10ms a|", {
a: items,
});
const queries = hot("a 399ms b 499ms |", {
a: "old",
b: "new",
});
const values: Record<string, SearchState> = {
a: { kind: "loading", query: "old" },
b: { kind: "loading", query: "new" },
c: { kind: "success", query: "new", items },
};
// When
const state = createSearchState(queries, (query) =>
query === "old" ? first : second,
);
// Then
expectObservable(state).toBe(
"a 399ms b 309ms c 189ms |",
values,
);
expectSubscriptions(first.subscriptions).toBe("300ms ^ 99ms !");
});
});
it("continues after a failed request", () => {
createScheduler().run(({ cold, hot, expectObservable }) => {
// Given
const failure = cold<readonly Product[]>("#");
const items = [{ id: "2", name: "New" }];
const success = cold<readonly Product[]>("10ms a|", {
a: items,
});
const queries = hot("a 399ms b 499ms |", {
a: "old",
b: "new",
});
const values: Record<string, SearchState> = {
a: { kind: "loading", query: "old" },
b: { kind: "error", query: "old" },
c: { kind: "loading", query: "new" },
d: { kind: "success", query: "new", items },
};
// When
const state = createSearchState(queries, (query) =>
query === "old" ? failure : success,
);
// Then
expectObservable(state).toBe(
"a 299ms b 99ms c 309ms d 189ms |",
values,
);
});
});
it("does not start a request when the query is cleared early", () => {
createScheduler().run((helpers) => {
const { cold, hot, expectObservable, expectSubscriptions } = helpers;
// Given
const response = cold<readonly Product[]>("a|", { a: [] });
const queries = hot("a 99ms b 299ms |", {
a: "old",
b: "",
});
const values: Record<string, SearchState> = {
a: { kind: "loading", query: "old" },
b: { kind: "idle", query: "" },
};
// When
const state = createSearchState(queries, () => response);
// Then
expectObservable(state).toBe("a 99ms b 299ms |", values);
expectSubscriptions(response.subscriptions).toBe([]);
});
});
it("reports an empty completion as an error", () => {
createScheduler().run(({ cold, hot, expectObservable }) => {
// Given
const response = cold<readonly Product[]>("|");
const queries = hot("a 399ms |", { a: "old" });
const values: Record<string, SearchState> = {
a: { kind: "loading", query: "old" },
b: { kind: "error", query: "old" },
};
// When
const state = createSearchState(queries, () => response);
// Then
expectObservable(state).toBe("a 299ms b 99ms |", values);
});
});
it("does not restart for equivalent normalized queries", () => {
createScheduler().run((helpers) => {
const { cold, hot, expectObservable, expectSubscriptions } = helpers;
// Given
const items: readonly Product[] = [];
const response = cold<readonly Product[]>("10ms a|", {
a: items,
});
const queries = hot("a 99ms b 399ms |", {
a: "old",
b: " old ",
});
const values: Record<string, SearchState> = {
a: { kind: "loading", query: "old" },
b: { kind: "success", query: "old", items },
};
// When
const state = createSearchState(queries, () => response);
// Then
expectObservable(state).toBe("a 309ms b 189ms |", values);
expectSubscriptions(response.subscriptions).toBe("300ms ^ 9ms !");
});
});
});
products-api.spec.ts
import { HttpClient, provideHttpClient } from "@angular/common/http";
import {
HttpTestingController,
provideHttpClientTesting,
} from "@angular/common/http/testing";
import { TestBed } from "@angular/core/testing";
import { firstValueFrom } from "rxjs";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { loadProducts, SEARCH_URL } from "./products-api";
let http: HttpClient;
let controller: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
http = TestBed.inject(HttpClient);
controller = TestBed.inject(HttpTestingController);
});
afterEach(() => {
controller.verify();
});
describe("product API", () => {
it("validates a successful response", async () => {
// Given
const items = [{ id: "1", name: "Camera" }];
// When
const result = firstValueFrom(loadProducts(http, "camera"));
const request = controller.expectOne(`${SEARCH_URL}?q=camera`);
request.flush(items);
// Then
expect(request.request.method).toBe("GET");
expect(await result).toEqual(items);
});
it("rejects invalid response data", async () => {
// Given
const invalid = [{ id: 1, name: "Camera" }];
// When
const result = firstValueFrom(loadProducts(http, "camera"));
const assertion = expect(result).rejects.toThrow(TypeError);
controller.expectOne(`${SEARCH_URL}?q=camera`).flush(invalid);
// Then
await assertion;
});
it("propagates HTTP errors", async () => {
// Given
const result = firstValueFrom(loadProducts(http, "camera"));
const assertion = expect(result).rejects.toMatchObject({
status: 503,
});
// When
controller.expectOne(`${SEARCH_URL}?q=camera`).flush(null, {
status: 503,
statusText: "Service Unavailable",
});
// Then
await assertion;
});
it("unsubscribes from a pending request", () => {
// Given
const subscription = loadProducts(http, "camera").subscribe();
const request = controller.expectOne(`${SEARCH_URL}?q=camera`);
// When
subscription.unsubscribe();
// Then
expect(request.cancelled).toBe(true);
});
});
Separate pure-function tests from stream tests. Given-When-Then is an optional convention for organizing setup, action and expectation. TestScheduler can verify emission times and cancellation of a previous subscription in virtual time. The supplied test starts the old query at 300 ms, replaces it at 400 ms and expects only the new result. It is not a real HTTP transport test. [13]
With HttpTestingController check method, parameters, invalid JSON, HTTP errors and unexpected requests; configure provideHttpClient before provideHttpClientTesting if using both. Separately test component destruction, clearing the field while loading, repeating an identical query and recovery by editing after failure. The demo does not retry an identical normalized query; a Retry button requires a separate event. Measure the time from typing to a current result instead of judging quality by subscription counts alone. [14]
The HTTP adapter tests below cover valid and invalid responses, an HTTP error and unsubscription; TestRequest.cancelled confirms state in the testing backend, not server-side cancellation. [14][23]
