Sub topic 6
Waiting for input: returning undefined
This chapter assumes you can already declare an httpResource with a URL that reads a signal, and that you know the resource's value(), status(), error() and isLoading() signals. If you need a refresher, see the earlier chapters on basic resources and reactive requests.
The problem: a request you don't want yet
A request function that always returns a URL fires a request as soon as the resource is created. That is often wrong. Consider these cases:
- A search box starts empty, and
/api/products?q=would return everything or an error. - A detail panel shows the item the user selected, but nothing is selected yet.
- A request needs a value that another signal supplies later, such as a logged-in user's id.
You could wrap the resource in an @if block or create it lazily. A simpler option is to let the request function say "nothing to fetch right now". It does this by returning undefined.
The rule
The request function passed to httpResource can return one of three things:
- A string URL.
- A request object such as
{ url, method, params, headers, body }. undefined.
When it returns undefined, the resource does not send a request. It becomes idle. The request function runs again whenever a signal it read changes. If it then returns a URL or request object, the resource leaves the idle state and starts loading.
import { Component, computed, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
title: string;
}
@Component({
selector: 'app-product-search',
template: `
<input
placeholder="Search products"
(input)="query.set($any($event.target).value)"
/>
@if (results.status() === 'idle') {
<p>Type at least two characters to search.</p>
}
@if (results.isLoading()) {
<p>Searching…</p>
}
@if (results.error()) {
<p>The search failed.</p>
}
<ul>
@for (p of results.value(); track p.id) {
<li>{{ p.title }}</li>
}
</ul>
`,
})
export class ProductSearchComponent {
query = signal('');
private term = computed(() => this.query().trim());
results = httpResource<Product[]>(
() => {
const term = this.term();
if (term.length < 2) {
return undefined;
}
return { url: '/api/products', params: { q: term, limit: '10' } };
},
{ defaultValue: [] },
);
}While the box is empty or holds one character, no network call happens. The template shows the hint. Once the user types a second character, the function returns a request object. The resource moves to loading and sends a GET request.
The trim() happens in a computed. That way, typing a trailing space does not change term(), and the request function does not run again for nothing.
What the resource looks like while idle
An idle resource is not an error and not a loading state. It has no request at all. These are the values you can rely on:
| Signal | Value while idle |
|---|---|
| `status()` | `'idle'` |
| `isLoading()` | `false` |
| `error()` | `undefined` |
| `value()` | `undefined`, or the `defaultValue` if you set one |
| `hasValue()` | `false` when there is no default value |
The status() signal returns a string literal in current Angular releases. Earlier previews used a ResourceStatus enum. If your project is on an older version, check the type that status() returns before comparing it to 'idle'.
The defaultValue option from the earlier chapter matters here. Without it, results.value() is undefined while idle, so the @for loop above would have to guard against that. With defaultValue: [], the template can iterate over value() directly in every state.
Returning to idle after a request
The transition also works in the other direction. Suppose the user clears the search box after results appeared. The request function now returns undefined, and three things happen:
- If a request is still in flight, the resource cancels it. A late response can no longer overwrite the idle state.
- The status becomes
'idle'. value()goes back toundefinedor to yourdefaultValue. The old results are not kept on screen.
This is usually what you want for a search box. If you would rather keep showing the last results, copy results.value() into your own signal or use a linkedSignal.
A second pattern: waiting for a selection
Idle requests are also useful when the input is an optional id. This example loads a product only after one has been chosen.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface ProductDetail {
id: number;
title: string;
description: string;
}
@Component({
selector: 'app-product-detail',
template: `
<button (click)="selectedId.set(1)">Product 1</button>
<button (click)="selectedId.set(2)">Product 2</button>
<button (click)="selectedId.set(undefined)">Clear</button>
@if (detail.hasValue()) {
<h2>{{ detail.value().title }}</h2>
<p>{{ detail.value().description }}</p>
} @else if (detail.isLoading()) {
<p>Loading…</p>
} @else if (detail.status() === 'idle') {
<p>Select a product.</p>
}
`,
})
export class ProductDetailComponent {
selectedId = signal<number | undefined>(undefined);
detail = httpResource<ProductDetail>(() => {
const id = this.selectedId();
return id === undefined ? undefined : `/api/products/${id}`;
});
}Two details deserve attention:
hasValue()is a type guard in the template. Inside the@if,detail.value()is typed asProductDetail, notProductDetail | undefined. This is often cleaner thandetail.value()?.title.- The check is
id === undefined, not!id. If your ids can be0, the falsy check would treat a valid id as "nothing selected".
Common errors
Returning an empty string or a placeholder URL
// Wrong: an empty string is not "no request".
results = httpResource<Product[]>(() => `/api/products?q=${this.query()}`);This sends a request for every value, including the empty one. Returning '' is no better. Always return undefined explicitly when you want the resource to wait.
Returning `null` or `false`
The request function's type allows undefined, not null or false. TypeScript will reject these. If your guard is written as condition && request, the result can be false, so use a ternary or an early return undefined instead.
Reading signals after the early return
Angular tracks the signals a request function reads each time it runs. If you return before reading a signal, that signal is not a dependency of that run.
results = httpResource<Product[]>(() => {
const q = this.query();
if (!q) {
return undefined; // sortOrder is not read on this run
}
return { url: '/api/products', params: { q, sort: this.sortOrder() } };
});This is fine. When q is empty, sortOrder cannot matter. Once q has text, the next run reads both signals, so both are tracked. It only becomes a bug if you rely on a signal that is never read on the path that actually runs. Read the signals that gate the request first, as above.
Calling `reload()` on an idle resource
reload() repeats the current request. An idle resource has no current request, so there is nothing to repeat. The call does nothing and returns false. If a button should trigger a fetch, change the signal that the request function reads. Do not call reload() on a resource that has not started.
Expecting a debounce
Returning undefined for short input does not delay the requests that follow. A user typing "angular" produces requests for an, ang, angu, and so on. Each new request cancels the previous one, so the app stays correct. The server still receives the requests, though. For a busy endpoint, debounce the input signal itself, for example with a timer before you call query.set, or with a debounced signal helper in your codebase.
When not to use an idle resource
An idle resource fits input-dependent reads. Some cases need a different tool:
- If the user clicks a button to submit data, that is a write. Use
HttpClientfor it, as a later chapter explains. - If the resource should exist only on some pages, scope it to the component or service that needs it. An idle resource costs almost nothing, but it is still extra state to understand.
Exercise
A component has userId = signal<number | null>(null) and this resource: user = httpResource<User>(() => /api/users/${this.userId()}). It fires a request to /api/users/null on creation. Rewrite the request function so that no request is sent until userId holds a number, and say which status() the resource reports before then. Make sure userId set to 0 still loads user 0.
Show answer
Use an explicit null check: user = httpResource<User>(() => { const id = this.userId(); return id === null ? undefined : /api/users/${id}; });. While userId is null, the function returns undefined, so no request is sent and status() is 'idle', with isLoading() false and value() undefined. Checking id === null instead of !id keeps 0 working as a valid id.
Exercise
A search resource has results on screen for the query "angular". The user deletes all the text, so the request function returns undefined. What happens to a request that is still in flight, and what do status() and value() report afterwards if the resource was created with { defaultValue: [] }?
Show answer
The in-flight request is cancelled, so a late response cannot overwrite the state. status() becomes 'idle', and value() returns the default value [], not the old results.