Sub topic 4
Reading value, status and errors in templates
This chapter assumes you know TypeScript, Angular components and templates, and signals (signal, computed, reading signals in templates). It also assumes you know basic HTTP: methods, status codes and query parameters. You have already declared a basic httpResource. Here you learn what it exposes and how to render each state without errors.
What an httpResource exposes
An httpResource returns an object whose members are signals. You call each one like a function, so a template that reads them re-renders whenever they change.
| Member | Type of the result | Meaning | Column |
|---|---|---|---|
| `value()` | `T \ | undefined` | The latest parsed response, or the default value |
| `status()` | a status string | Which phase the resource is in | |
| `error()` | an error or `undefined` | The failure of the latest request | |
| `isLoading()` | `boolean` | `true` while a request is in flight | |
| `hasValue()` | `boolean` | `true` when `value()` is safe to read | |
| `headers()` | `HttpHeaders \ | undefined` | Response headers of the latest response |
| `statusCode()` | `number \ | undefined` | HTTP status code of the latest response |
The last two are specific to httpResource. The others belong to every Angular resource.
The status values
status() returns one of six strings. Each one tells you what value() and error() hold at that moment.
| Status | Meaning | `value()` | `isLoading()` |
|---|---|---|---|
| `idle` | No request is wanted, because the request function returned `undefined` | default or `undefined` | `false` |
| `loading` | First request, or the request changed, is in flight | default or `undefined` | `true` |
| `reloading` | `reload()` is repeating the same request | previous value | `true` |
| `resolved` | The request succeeded | the response | `false` |
| `error` | The request failed | not readable (see below) | `false` |
| `local` | Your code wrote a value with `set()` or `update()` | the local value | `false` |
The difference between loading and reloading matters for the user interface. When a signal that the request reads changes, the resource goes to loading and the old value is discarded. When you call reload(), it goes to reloading and the old value stays visible. That lets you show stale data with a small spinner instead of blanking the page.
Rendering the common states
The simplest template reads isLoading(), error() and value() separately.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user',
template: `
<button (click)="next()">Next user</button>
@if (user.isLoading()) {
<p>Loading…</p>
}
@if (user.error()) {
<p>Could not load the user.</p>
}
<p>{{ user.value()?.name }}</p>
`,
})
export class UserComponent {
userId = signal(1);
user = httpResource<User>(() => `/api/users/${this.userId()}`);
next() {
this.userId.update((id) => id + 1);
}
}This works, but it has two weaknesses. In an error state, the last line may try to read value(), which is a problem in current Angular versions (see the next section). It also has no way to tell "nothing was requested" from "the response was empty".
value() and the error state
value() is undefined until the first response arrives, unless you set defaultValue (covered in a later chapter). That is why templates use user.value()?.name.
In recent Angular versions, reading value() while the resource is in the error state throws. A template that reads value() unconditionally can then fail during rendering instead of showing your error message. Use hasValue() as the guard. It returns false in the error state and in any state where there is no value.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-guarded',
template: `
@if (user.hasValue()) {
<h2>{{ user.value().name }}</h2>
}
@if (user.error()) {
<p class="error">Could not load the user.</p>
}
@if (user.isLoading()) {
<p>Loading…</p>
}
`,
})
export class UserGuardedComponent {
userId = signal(1);
user = httpResource<User>(() => `/api/users/${this.userId()}`);
}hasValue() also narrows the type. Inside the @if block the compiler treats user.value() as User, not User | undefined, so you do not need ?..
Because hasValue() stays true during reloading, the block above keeps showing the old user while a reload runs. It disappears during loading, because the value was discarded.
Switching on status
When each state needs its own layout, switch on status() instead of combining booleans. The branches are mutually exclusive, so you cannot render two of them at once by accident.
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-status',
template: `
@switch (user.status()) {
@case ('idle') {
<p>Choose a user.</p>
}
@case ('loading') {
<p>Loading…</p>
}
@case ('error') {
<p>Failed: {{ user.error()?.message }}</p>
<button (click)="user.reload()">Retry</button>
}
@default {
<h2>{{ user.value()?.name }}</h2>
@if (user.isLoading()) {
<small>Refreshing…</small>
}
}
}
`,
})
export class UserStatusComponent {
userId = signal<number | undefined>(undefined);
user = httpResource<User>(() => {
const id = this.userId();
return id === undefined ? undefined : `/api/users/${id}`;
});
}The @default branch covers resolved, reloading and local. All three have a readable value. The nested isLoading() check shows the "Refreshing…" hint only during reloading.
The Retry button calls reload(), which repeats the current request and moves the resource from error to reloading.
Reading errors
error() holds the failure of the latest request, and it is undefined otherwise. For a failed HTTP call it is an HttpErrorResponse. That means a 404 or a 500 arrives as an error, not as a value. A network failure and a server error both appear here, and error()?.message works for both.
Two further points help when you build error messages:
- A new request clears the error. As soon as a signal in the request changes, the status becomes
loadinganderror()returnsundefined. - An exception thrown by a
parsefunction, or by the request function, also lands inerror(), so one error branch covers transport and validation problems.
Response metadata
statusCode() and headers() describe the latest successful response. They are undefined before any response arrives.
import { Component } from '@angular/core';
import { httpResource } from '@angular/common/http';
@Component({
selector: 'app-meta',
template: `
@if (items.statusCode(); as code) {
<p>Server answered with {{ code }}</p>
}
<p>Total: {{ items.headers()?.get('X-Total-Count') }}</p>
`,
})
export class MetaComponent {
items = httpResource<string[]>(() => '/api/items');
}Reading a response header only works when the server exposes it. Under cross-origin requests the browser hides headers that the server does not list in Access-Control-Expose-Headers.
Common mistakes
- Reading
value()outside a guard. In the error state this can throw. Guard withhasValue()or testerror()first. - Assuming
isLoading()isfalsemeans "has data". The resource may beidleor inerror. UsehasValue()for that question. - Showing an empty state while loading. An empty list and "not loaded yet" look alike unless you check
isLoading()orstatus(). - Expecting the old value during
loading. Onlyreload()keeps it. A changed request signal discards it. - Calling the signals without parentheses.
user.isLoadingis a function, which is always truthy. Always writeuser.isLoading().
Exercise
A product page shows {{ product.value().title }} inside an @if (product.hasValue()) block. A user clicks a "Refresh" button that calls product.reload(), and later navigates so that the product ID signal changes. What does the user see in each case, and what are the statuses?
Show answer
On refresh the status is reloading. hasValue() stays true, so the old title stays visible, and isLoading() is true, so you can show a small spinner. When the ID signal changes, the status becomes loading and the previous value is discarded. hasValue() is false, so the title disappears until the new response arrives and the status becomes resolved.
Exercise
Why is @if (user.error()) { ... } @else { {{ user.value().name }} } risky for a resource that starts with no request, and what would you use instead?
Show answer
When the request function returns undefined, the status is idle, error() is undefined, and value() is also undefined. The @else branch would read name from undefined. Use @if (user.hasValue()) for the success branch, and handle idle separately, for example with @switch (user.status()).