Sub topic 8
Providing a default value
This chapter covers the defaultValue option of httpResource. You should already be comfortable with signals, computed, and the control flow blocks @if and @for. You should also know what the earlier chapters on resource state and idle requests covered.
The problem: value() is possibly undefined
An httpResource has no data until the first response arrives. While the resource is idle, loading, or failed, there is nothing to put in value(). The type reflects that, so value() is T | undefined.
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
title: string;
}
const products = httpResource<Product[]>(() => '/api/products');
// products.value() has the type Product[] | undefinedEvery consumer must handle undefined. In a template that means optional chaining, @if guards, or the ?? [] operator. In TypeScript code it means narrowing before every use. For collections this is tedious, because an empty list is usually the right thing to show while nothing has loaded.
The defaultValue option removes undefined from the type. It also gives the resource a stand-in value to expose until real data exists.
Declaring a default value
Pass defaultValue in the options object, which is the second argument of httpResource.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
title: string;
}
@Component({
selector: 'app-search',
template: `
<input (input)="query.set($any($event.target).value)" />
<p>{{ results.value().length }} results</p>
<ul>
@for (p of results.value(); track p.id) {
<li>{{ p.title }}</li>
}
</ul>
`,
})
export class SearchComponent {
query = signal('');
results = httpResource<Product[]>(
() => {
const q = this.query();
if (!q) {
return undefined;
}
return { url: '/api/products', params: { q, limit: '10' } };
},
{ defaultValue: [] },
);
}results.value() is now typed as Product[]. The template calls .length and iterates without any guard. Before the user types anything, the request function returns undefined, the resource stays idle, and value() returns [].
The default must be assignable to the resource's result type. defaultValue: 'none' on a Product[] resource is a compile error.
When the default is visible
The default is not only an initial value. The resource falls back to it in every state that has no real data. This table shows what value() returns, assuming defaultValue is set.
| Status | Meaning | `value()` returns |
|---|---|---|
| `idle` | The request function returned `undefined`. | The default |
| `loading` | The first request, or a new request after the signals changed. | The default |
| `reloading` | `reload()` was called on a resource that already has data. | The previous response |
| `resolved` | A response arrived and was parsed. | The response |
| `error` | The request or the parse step failed. | See the callout below |
| `local` | Code called `value.set()` or `value.update()`. | The locally set value |
The difference between loading and reloading matters. When a signal that the request depends on changes, the old response no longer matches the new request. The resource therefore drops it and shows the default until the new response arrives. A call to reload() repeats the same request, so the resource keeps the old data on screen while the refresh runs.
Guarding reads with hasValue()
Even with a default, value() never tells you whether the data is real. Both an empty server response and a resource that has not loaded yet produce []. The hasValue() method returns true only when the resource holds actual data, so it is also the safe way to read value() in code that might run during an error.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
title: string;
}
@Component({
selector: 'app-product-list',
template: `
@if (products.error()) {
<p>Could not load products.</p>
} @else if (products.isLoading()) {
<p>Loading…</p>
} @else if (products.value().length === 0) {
<p>No products found.</p>
} @else {
<ul>
@for (p of products.value(); track p.id) {
<li>{{ p.title }}</li>
}
</ul>
}
`,
})
export class ProductListComponent {
category = signal('books');
products = httpResource<Product[]>(
() => ({ url: '/api/products', params: { category: this.category() } }),
{ defaultValue: [] },
);
}The order of the branches does the work here. The error branch comes first, so the template never reads value() in the error state. The loading branch comes second, so the user does not see "No products found." while the first response is still on its way. Only after both are ruled out does an empty value() mean the server returned an empty list.
Choosing a good default
The default should be a value your template can render correctly without special cases. These are the usual choices.
- Collections: use
[]. Loops render nothing and.lengthis0. - Counts or totals: use
0. - Text: use
''. - Objects: use an object with the same shape as the response, such as
{ id: 0, name: '' }. Fill every field with a neutral value so property reads do not fail.
For single records, a default can hide the difference between "no user" and "a user with an empty name". If the page must show a different layout for a missing record, leave the default out and keep T | undefined. The undefined is then a useful signal.
import { httpResource } from '@angular/common/http';
interface Settings {
theme: 'light' | 'dark';
pageSize: number;
}
const fallback: Settings = { theme: 'light', pageSize: 20 };
export const settings = httpResource<Settings>(() => '/api/settings', {
defaultValue: fallback,
});A real fallback like this one works well. The page renders with sensible settings immediately and then updates when the server's settings arrive.
Combining defaultValue with parse
Both parse and defaultValue appear in the same options object. The parse function converts the raw response into the result type, and the default must already have that result type.
import { httpResource } from '@angular/common/http';
interface Product {
id: number;
title: string;
}
function parseProducts(raw: unknown): Product[] {
if (!Array.isArray(raw)) {
throw new Error('Expected an array of products');
}
return raw.map((item) => {
const p = item as Partial<Product>;
if (typeof p.id !== 'number' || typeof p.title !== 'string') {
throw new Error('Unexpected product payload');
}
return { id: p.id, title: p.title };
});
}
export const products = httpResource<Product[]>(() => '/api/products', {
parse: parseProducts,
defaultValue: [],
});The default is never passed through parse. If parse throws, the resource goes to the error state. It does not fall back to the default.
Common mistakes
- Treating the default as "no data".
value().length === 0is true both before loading and after an empty response. CheckisLoading()orstatus()when the difference matters. - Reading
value()in the error state. Checkerror()first, or usehasValue(), as shown above. - Using a default that hides a missing record. A blank object default makes a failed or empty lookup look like a real record with empty fields.
- Mutating the default. Calling
pushonresults.value()can change the shared default array. Treat resource values as read-only and usevalue.set()orvalue.update()with new arrays. - Expecting the default to survive a signal change with data on screen. When a signal in the request changes, the previous response is dropped and the default shows until the new response arrives. If you want old data to stay visible, use
reload()instead, or keep the last good value in a separate signal.
Summary
defaultValuemakesvalue()returnTinstead ofT | undefined.- The default shows while the resource is idle or loading, and the previous response shows while it reloads.
- A default cannot tell "not loaded" from "empty". Use
status(),isLoading(), orhasValue()for that. - In the error state, guard reads rather than relying on the default.
Exercise
A resource is declared as httpResource<string[]>(() => '/api/tags', { defaultValue: [] }). The template shows "No tags yet." when tags.value().length === 0. Users report seeing "No tags yet." for a moment on every page load, even when tags exist. What is the cause, and how do you fix the template?
Show answer
While the first request is loading, value() returns the default [], so the length check is true. Check tags.isLoading() before the empty check, and check tags.error() before both. For example: @if (tags.error()) { … } @else if (tags.isLoading()) { Loading… } @else if (tags.value().length === 0) { No tags yet. } @else { …list… }.
Exercise
Why does a resource with defaultValue show the default again after a signal used in its request changes, but keep its old data after reload()?
Show answer
A signal change means the request is different, so the old response belongs to a different request. The resource moves to loading and shows the default until the new response arrives. reload() repeats the same request, so the resource moves to reloading and keeps the previous response until the refresh finishes.