Sub topic 9
Building a Debounced Search: Signal, RxJS Operators, Signal
This chapter combines toObservable and toSignal in one feature, a search box that waits for the user to pause typing and then calls an API.
What you need before this chapter
This chapter assumes you can do the following:
- Write a standalone Angular component and use
inject(). - Create and read signals with
signal(). - Use RxJS operators such as
mapandswitchMap. - Read TypeScript generics and union types.
It also assumes you know that toSignal and toObservable need an injection context. Field initializers and constructors provide one.
Why this problem needs both tools
A search box has two jobs that belong to different tools:
- Holding the current text. This is synchronous state that the template reads and writes. A signal fits.
- Deciding when to call the server. This depends on time: wait for a pause, drop repeated values, cancel a request that is no longer wanted. RxJS operators fit.
The pipeline goes from signal to stream and back to signal. The template only sees signals, and the timing logic stays in one RxJS pipe.
Step 1: the query signal
The signal is the single source of truth for what the user typed.
query = signal('');
onInput(event: Event) {
this.query.set((event.target as HTMLInputElement).value);
}Writing a typed handler is safer than $any($event.target).value in the template. The $any form compiles, but it turns off type checking for that expression.
Step 2: from signal to stream
toObservable(this.query) returns an observable of the query's values. Two facts from earlier chapters matter here:
- It reads the signal inside an effect. Values are delivered asynchronously, and if the signal is set several times before the effect runs, only the latest value is emitted.
- The effect runs once initially, so the observable emits the starting value (
'') shortly after creation. Your operators must tolerate that first empty string.
Both facts suit a search box. Skipping intermediate values is harmless because debounceTime would discard them anyway.
Step 3: the operators
Each operator solves one specific problem.
| Operator | Problem it solves |
|---|---|
| `debounceTime(300)` | Waits until 300 ms pass without a new value, so each keystroke does not fire a request. |
| `map(q => q.trim())` | Normalizes the text so trailing spaces do not count as a new search. |
| `distinctUntilChanged()` | Drops a value equal to the previous one. Typing `a`, then `ab`, then deleting back to `a` within 300 ms leaves two identical values after the debounce. |
| `switchMap` | Starts the request for the newest value and unsubscribes from the previous one. For `HttpClient`, unsubscribing aborts the in-flight request. |
Order matters. Put map before distinctUntilChanged so the comparison uses the normalized text. Put debounceTime before switchMap, otherwise every keystroke starts, and cancels, a request.
Step 4: from stream back to signal
toSignal subscribes to the final observable and exposes the latest value. The observable does not emit synchronously, so the signal needs an initialValue. Without one, its type would be T | undefined, and every template read would need a guard.
The first complete version
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, map, of, switchMap } from 'rxjs';
@Component({
selector: 'app-search',
template: `
<input [value]="query()" (input)="onInput($event)" placeholder="Search" />
<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(
map((q) => q.trim()),
debounceTime(300),
distinctUntilChanged(),
switchMap((q) =>
q.length < 2
? of([] as string[])
: this.http.get<string[]>('/api/search', { params: { q } }),
),
),
{ initialValue: [] as string[] },
);
onInput(event: Event) {
this.query.set((event.target as HTMLInputElement).value);
}
}The application must register provideHttpClient() in its providers. Otherwise inject(HttpClient) throws.
The q.length < 2 branch avoids sending a request for an empty or one-letter query. It returns of([]) instead of filtering the value out. If you used filter(q => q.length >= 2), clearing the box would never emit, and the old results would stay on screen.
What happens when the user types
Suppose the user types an, pauses, and then types g 100 ms after the pause starts. The table shows the time since the first keystroke.
| Time (ms) | Event | Pipeline effect |
|---|---|---|
| 0 | User types `a` | `query` is `a`. The effect emits it, and the debounce timer starts. |
| 80 | User types `n` | `query` is `an`. The timer restarts. |
| 380 | Timer expires | `an` passes `distinctUntilChanged`. `switchMap` sends `GET /api/search?q=an`. |
| 480 | User types `g` | `query` is `ang`. The debounce timer starts. The request for `an` is still running. |
| 520 | Response for `an` arrives | `results` updates to the `an` matches. |
| 780 | Timer expires | `switchMap` sends the request for `ang`. If the `an` request were still pending, it would be cancelled now. |
Between 480 and 780 ms the list shows results for an while the box shows ang. This lag is the cost of debouncing. The next section shows how to make it visible to the user.
Adding loading and error state
The first version has two weaknesses:
- The user gets no feedback while a request is running.
- A failed request kills the pipeline. When an observable errors, the stream is finished.
toSignalstores the error, and readingresults()rethrows it. Later typing never produces a request.
The fix is to model the state explicitly and catch errors on the inner observable, inside switchMap.
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,
map,
of,
startWith,
switchMap,
} from 'rxjs';
type SearchState = {
status: 'idle' | 'loading' | 'done' | 'error';
results: string[];
};
const IDLE: SearchState = { status: 'idle', results: [] };
const LOADING: SearchState = { status: 'loading', results: [] };
const FAILED: SearchState = { status: 'error', results: [] };
@Component({
selector: 'app-search',
template: `
<input [value]="query()" (input)="onInput($event)" placeholder="Search" />
@switch (state().status) {
@case ('loading') {
<p>Searching...</p>
}
@case ('error') {
<p>The search failed. Edit the text to try again.</p>
}
@case ('done') {
<ul>
@for (r of state().results; track r) {
<li>{{ r }}</li>
} @empty {
<li>No matches</li>
}
</ul>
}
}
`,
})
export class Search {
private http = inject(HttpClient);
query = signal('');
state = toSignal(
toObservable(this.query).pipe(
map((q) => q.trim()),
debounceTime(300),
distinctUntilChanged(),
switchMap((q) =>
q.length < 2
? of(IDLE)
: this.http.get<string[]>('/api/search', { params: { q } }).pipe(
map((results): SearchState => ({ status: 'done', results })),
catchError(() => of(FAILED)),
startWith(LOADING),
),
),
),
{ initialValue: IDLE },
);
onInput(event: Event) {
this.query.set((event.target as HTMLInputElement).value);
}
}Three details make this version work:
catchErroris insideswitchMap. An error on the inner HTTP observable is replaced byFAILED, and the inner observable completes. The outer stream keeps running, so the next query starts a new request. IfcatchErrorsat afterswitchMapin the outer pipe, it would still turn the error into a value, but the outer stream would complete and the pipeline would be dead.startWith(LOADING)is on the inner observable. Each new search emitsLOADINGimmediately, then the result. Because it is insideswitchMap, it runs once per request, not once per pipeline.- The state is one object. One signal holds status and results together, so they cannot disagree. Two separate signals updated from
tapwould allow a moment where the status saysdoneand the results are old.
The loading message appears only after the debounce delay, because switchMap runs only then. If you want feedback sooner, derive a "pending" flag by comparing the live query() with the last query that was sent. That is a computed over two signals.
Common errors in this pattern
Calling `toSignal` outside an injection context
Writing toSignal(...) inside an event handler or a setTimeout throws an error about needing an injection context. Create the signal in a field initializer or constructor. If you must create it later, pass { injector } as shown in an earlier chapter.
Creating the pipeline inside a computed or effect
toSignal creates a subscription. Calling it in computed() or effect() would create a new subscription every time the function reruns. Angular blocks toSignal there by default. Build the pipeline once, as a field.
Putting the HTTP call in `tap` or `subscribe`
This works, but you lose cancellation. Without switchMap, a slow response for an old query can arrive after a fast response for a newer one and overwrite it. The user then sees results for the wrong text. switchMap guarantees that only the latest request's result is delivered.
Expecting a request on every keystroke
toObservable can skip values and debounceTime removes more. This behavior is intended. If a test sets the signal three times in a row and expects three emissions, it will fail.
Forgetting that `''` is emitted first
The first emission from toObservable is the starting value. In the first version it reaches switchMap after the debounce and takes the of([]) branch. That is harmless, but without the length check you would send GET /api/search?q= on page load.
Reading the signal in a way that rethrows
If the stream errors and you did not catch it, state() throws on every read. This can break the whole template. Catch errors close to the source, as shown above.
When this pattern is the wrong choice
Not every signal needs a stream. Use the pipeline when you need time-based operators such as debounce, throttle, or cancellation of stale requests. If you only need a value derived from other signals, use computed(). A computed is synchronous, cheap, and has no subscription to manage.
A debounce also adds a fixed delay to every search. For a small, local list, filtering with computed() on every keystroke is simpler and feels faster.
Summary of the working model
- The signal holds the current input. The stream handles timing and cancellation. The final signal holds what the template displays.
toObservableemits asynchronously, starting with the initial value, and only the latest value of a burst.toSignalneeds aninitialValuehere, because the HTTP observable does not emit synchronously.- Errors must be turned into values inside
switchMapso the pipeline survives.
Exercise
In the loading-state version, the user types cat, waits for results, then deletes the text so the box is empty. What does state() hold afterwards, and which line of the pipeline decides it?
Show answer
It holds IDLE, with an empty results list. After the 300 ms debounce the trimmed query is '', which is different from cat, so distinctUntilChanged lets it through. switchMap sees q.length < 2 and returns of(IDLE). The old cat results are replaced, so the list disappears.
Exercise
A teammate moves catchError(() => of(FAILED)) from inside the switchMap callback to the end of the outer pipe. The API returns a 500 for the query bad, and the user then types good. What happens, and why?
Show answer
The 500 makes the inner HTTP observable error. The outer catchError turns that error into FAILED, but the outer stream then completes, so the pipeline stops. Typing good still updates query, but nothing reaches switchMap, so no request is sent and the signal keeps showing the failed state. Placing catchError inside switchMap keeps the outer stream alive.
Exercise
Write the changes needed to also ignore queries that differ only by letter case, so Cat and cat count as the same search.
Show answer
Normalize in the existing map, before debounceTime: map((q) => q.trim().toLowerCase()). Because distinctUntilChanged comes after this map, it compares the lowercased text and drops cat after Cat. The input element still shows what the user typed, because query itself is not changed.