Stato o eventi: due modelli reattivi
Un signal espone il valore corrente in modo sincrono tramite il getter. Angular registra le dipendenze lette in un contesto reattivo; computed valuta su richiesta, memorizza il risultato e segue soltanto le dipendenze lette. Modificare un signal non aggiorna sincronicamente il DOM. [1]
Un Observable può emettere zero, uno o più valori, in modo sincrono o asincrono, completarsi o fallire. Non deve necessariamente esporre un valore corrente. Un Observable normale può avviare lavoro separato per ogni sottoscrittore; Subject distribuisce eventi a più destinatari. BehaviorSubject richiede un valore iniziale e fornisce il valore corrente a un nuovo sottoscrittore attivo. Non sostituire un registro di eventi con un solo signal. [2][3] [15]
Stato del componente e valori derivati
La ricerca conserva il testo in signal e ricava la query dopo trim con computed. Non serve un altro signal scrivibile sincronizzato da effect. Con una lista disponibile, filtro locale, numero di risultati e selezione possono spesso essere derivati. [1][4]
Signals usa Object.is per impostazione predefinita. Mutare un array sul posto può impedire l'aggiornamento atteso; crea un nuovo riferimento. asReadonly impedisce set e update tramite quel riferimento ma non congela l'oggetto. Nel template OnPush, Angular traccia le letture e marca il componente per l'aggiornamento. Misura calcoli, richieste e rendering invece di presumere vantaggi. [1]
Scelta del modello e condivisione dei dati
Signals si adatta allo stato dei form, ai filtri e ai calcoli derivati; Observable agli eventi, ai messaggi WebSocket, alla concorrenza e alle regole temporali. Subject è utile per comandi di cui conta ogni singola occorrenza. linkedSignal consente uno stato dipendente modificabile, ad esempio una selezione da ricalcolare quando cambia la lista. Evita di copiare segnali tramite effect. [1][4][18]
HttpClient restituisce un Observable freddo: due sottoscrizioni indipendenti normalmente avviano due richieste. Condividi i risultati consapevolmente, per esempio con shareReplay({ bufferSize: 1, refCount: true }); refCount disconnette una sorgente ancora attiva quando resta senza sottoscrittori, ma non fornisce TTL automatico né invalidazione delle risposte completate. Isola i dati privati per utente. [5][19]
Contratto di ricerca e dati HTTP
Approfondimenti: Promises e async/await in JavaScript (EN).
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;
}
La demo richiede due caratteri dopo trim. Il ritardo di 300 ms e la lunghezza minima sono scelte dimostrative, non standard UX. Un'unione discriminata distingue idle, loading, success ed error, quindi un risultato vuoto non è un errore. Ogni stato contiene la query che lo ha prodotto.
HttpClient.get<unknown> rende esplicita la validazione. Un tipo generico non valida JSON. Il parser richiede un array di record con id e name non vuoti, di tipo stringa, e rifiuta ID duplicati usati da track. Separa struttura e valori con guard clauses. In produzione aggiungi contratto del backend, limiti e messaggi localizzati. [5]
Trasporto robusto e contratto del flusso
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));
}
L’adapter loadProducts separa il trasporto HTTP dal componente e limita l’attesa del backend a dieci secondi. È una scelta dimostrativa; timeout non comprende i ritardi degli interceptor né i 300 ms precedenti la richiesta. [5]
Il contratto prevede una risposta per query. first() prende il primo valore e segnala un errore se la sorgente termina senza emettere; altrimenti la vista potrebbe restare in caricamento. Un array vuoto è valido. La cancellazione della sottoscrizione tramite switchMap non è un errore e non deve mostrare un fallimento. [20]
RxJS e politiche di concorrenza
Approfondimenti: Debounce vs Throttle (EN).
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)),
);
}
Approfondimenti: Long Tasks, Main Thread and INP (EN).
La ricerca dà priorità all'ultima query tramite switchMap. Una nuova emissione normalizzata annulla la precedente sottoscrizione interna, timer o HTTP incluso. Il timer è dentro switchMap: debounceTime a monte permetterebbe alla vecchia richiesta di finire durante l'attesa. distinctUntilChanged ignora valori normalizzati consecutivi uguali. [3][6][7]
concatMap accoda operazioni, mergeMap consente concorrenza limitabile, exhaustMap ignora emissioni durante un'operazione attiva. Scegli in base alla semantica e non alla velocità presunta. Non usare switchMap per scritture senza analizzarne le conseguenze. Annullare HTTP sul client non garantisce l'annullamento del lavoro già eseguito dal server. [3][5]
Conversione tra signal e Observable
toSignal sottoscrive alla creazione. Invocalo una volta al confine del componente, non in getter, computed o template. Fornisci initialValue o gestisci undefined. requireSync è adatto solo a fonti che garantiscono la prima emissione sincrona, non all'HTTP ordinario. Al completamento resta l'ultimo valore; un errore non gestito viene sollevato alla lettura del signal. [8]
toObservable usa un effetto ed emette lo stato stabilizzato; più scritture possono diventare una sola emissione. Non è un registro dei clic. computed visibleState nasconde i risultati precedenti anche prima della nuova emissione. catchError nel flusso della singola query crea uno stato error e permette query successive differenti. Entrambe le conversioni normalmente richiedono un contesto di injection o un Injector esplicito. [8] [17]
Componente, template e ciclo di vita
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);
});
Metti i file nello stesso percorso del componente standalone. L'entry point configura HttpClient; /api/products è un contratto di esempio per il tuo backend. Il template usa @let, @switch, @for, un'etichetta e un messaggio di stato. (input) è un binding di Angular, non un attributo nativo oninput. CSS è separato.
Il signal di risultato appartiene al componente; toSignal normalmente si disiscrive quando questo viene distrutto. Usa AsyncPipe nel template o takeUntilDestroyed per sottoscrizioni manuali (passa DestroyRef fuori dal contesto di injection). Inserisci la terminazione dopo gli operatori che creano sottoscrizioni interne. Usa effect per sincronizzazione esterna con onCleanup e computed per le derivazioni. [4][8][9] [16]
API resource e migrazione graduale
Angular 22 indica resource, httpResource e rxResource come stabili. Versioni precedenti avevano altri stati e possono offrire API diverse. resource collega parametri a letture asincrone; httpResource espone risposta e stato HTTP tramite signal e avvia richieste senza sottoscrizione manuale. rxResource usa una fonte Observable. Valuta queste astrazioni per letture semplici. [10][11][12]
resource non è un meccanismo sicuro per mutazioni: cambi di parametri o distruzione possono interrompere il caricamento. Per scritture usa comandi espliciti con gestione di conflitti, idempotenza ed errori. Mantieni i contratti Observable solidi e converti al confine della vista. Non riscrivere tutto il progetto solo per i Signals. [10]
Alternativa: httpResource all’invio del form
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 };
}
Se la richiesta deve seguire l’invio del form, usa questa factory httpResource. Creala una sola volta in un contesto di injection, ad esempio nell’inizializzatore di un campo. Passa il testo a submit all’invio, non a ogni input. undefined evita richieste troppo brevi; parse riutilizza lo stesso parser. [11][21]
Controlla error(), isLoading() e hasValue() prima di value(); leggere il valore in stato di errore può generare un’eccezione. retry usa reload(), che non avvia necessariamente una richiesta mentre il caricamento è già in corso. In reloading il valore precedente può rimanere disponibile. Questa alternativa non implementa il ritardo di 300 ms né il template completo precedente; RxJS resta utile per regole temporali complesse. [21][22]
Angular 22 offre anche debounced sperimentale in @angular/core. Durante l’attesa la risorsa può mantenere il valore stabilizzato precedente. Combinarlo con resource non garantisce quindi la cancellazione a ogni digitazione. Verifica stato e semantica; l’esempio principale mantiene RxJS stabile. [24]
Test e criteri di accettazione
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);
});
});
Separa test di funzioni pure e test dei flussi. Given-When-Then è una convenzione facoltativa per preparazione, azione e aspettativa. TestScheduler verifica i tempi di emissione e annullamento in tempo virtuale. Il test avvia la vecchia query a 300 ms, la sostituisce a 400 ms e attende solo il nuovo risultato. Non verifica il trasporto HTTP reale. [13]
Con HttpTestingController controlla metodo, parametri, JSON non valido, errori HTTP e richieste inattese; configura provideHttpClient prima di provideHttpClientTesting se usi entrambi. Verifica separatamente distruzione, svuotamento del campo durante il caricamento, query identica e recupero modificando il testo dopo un errore. La demo non ripete query normalizzate identiche; Retry richiede un evento separato. Misura il tempo tra digitazione e risultato corrente. [14]
I test dell’adapter coprono risposte valide e non valide, un errore HTTP e la cancellazione della sottoscrizione; TestRequest.cancelled conferma lo stato nel backend di test, non la cancellazione sul server. [14][23]
