Sub topic 9
Building a debounced search: signal, RxJS operators, signal
This chapter assumes you know signal(), computed(), HttpClient, and the RxJS operators switchMap and debounceTime. You also need to know what an injection context is, and how toSignal and toObservable behave from the earlier chapters.
A search box is a good test of mixing the two tools. The typed text is state, so a signal fits. Waiting for a pause in typing and cancelling stale requests are stream problems, so RxJS fits. The results are state again, because the template reads them.
The shape of the pipeline
The signal stays at both ends. The RxJS part sits in the middle, where time matters.
The component
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, debounceTime, distinctUntilChanged, of, switchMap } from 'rxjs';
@Component({
selector: 'app-search',
template: `
<input (input)="query.set($any($event.target).value)" />
<ul>
@for (r of results(); track r) {
<li>{{ r }}</li>
}
</ul>
`,
})
export class Search {
private http = inject(HttpClient);
query = signal('');
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((q) =>
this.http
.get<string[]>('/api/search', { params: { q } })
.pipe(catchError(() => of([] as string[]))),
),
),
{ initialValue: [] as string[] },
);
}The app must call provideHttpClient() in its configuration, or inject(HttpClient) fails.
Walking through each step
- The input handler calls
query.set(...). Nothing else runs in the handler. toObservable(this.query)emits the query value from an effect. It also emits the initial empty string once, soon after creation.debounceTime(300)waits for 300 ms of silence and then passes along the latest value only.distinctUntilChanged()drops a value equal to the previous one. This matters when the user types a character and deletes it within the debounce window.switchMapstarts a request and unsubscribes from the previous one, so a slow response for an old query cannot overwrite a newer result.toSignalsubscribes once and writes each result to theresultssignal.initialValuemakes the typeSignal<string[]>rather thanSignal<string[] | undefined>, and the template has an array to loop over before any response arrives.
Both conversions happen in a field initializer. A field initializer runs in the component's injection context, so no injector option is needed. Cleanup is automatic: when the component is destroyed, toSignal unsubscribes, which cancels any request in flight, and toObservable stops its internal effect.
Why catchError sits inside switchMap
If an error reaches the outer stream, the stream ends. After that, toSignal rethrows the error whenever the template reads results(). The search would stop working until the component is recreated.
Putting catchError on the inner HTTP observable handles the failure for that single request. The inner observable then completes with an empty array, and the outer stream stays alive for the next query.
Refining the pipeline
The fixed 300 ms value is a trade-off. A shorter delay feels faster but sends more requests. A longer delay sends fewer requests but feels slow.
You can skip empty queries by adding filter((q) => q.trim().length > 0) before switchMap. With that filter, clearing the input leaves the old results on screen, because no new value reaches toSignal. To clear them, map empty input to of([]) inside switchMap instead.
Timing to expect
Because toObservable emits from an effect, a value set and then immediately overwritten in the same tick is skipped. This is harmless here, since debouncing discards intermediate values anyway. Tests that expect an emission straight after query.set(...) need to flush effects first, and they need to advance fake time past the debounce.
Exercise
A user types "a", "ab" and "abc" with 100 ms between keystrokes. How many HTTP requests does the component send, and for which query? What would change if you replaced switchMap with mergeMap?
Show answer
One request, for "abc". Each keystroke restarts the 300 ms debounce timer, so only the last value passes after the pause. With mergeMap, a request that is still running would not be cancelled when a new query arrives. Slow responses could then arrive out of order, and an old result could overwrite a newer one.
Exercise
Why does the example use catchError on the inner HTTP observable instead of on the outer pipe?
Show answer
An error that reaches the outer stream ends it, and toSignal then rethrows the error whenever the signal is read. Handling the error on the inner observable keeps the outer stream alive, so later queries still work.