Blog

Part 19 · Loading Data with resource and httpResource in Angular

A resource is a signal that loads its own value. This part covers resource and httpResource, their status signals, reload, local changes, skipping a load, and how a new request cancels the old one.

Loading data means waiting. While you wait, the page has to say “Loading…”. If the load fails, it has to say so. And if the user asks for something else before the first answer arrives, the old answer must not win. In Part 15 we wrote all of that by hand, with a loading flag and an error field.

This part covers resource and httpResource. Each one is a signal that loads its own value, and it keeps the status, the error and the value for you. We’ll see what each status means, how to reload, how to change the value locally, how to skip a load, and how a new request cancels the one before it. It builds on signals from Part 3 and HttpClient from Part 18. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

Paste this into src/app/app.ts. It loads a user’s name when you click a button. The “server” is a Promise, as in Part 15: user 1 takes 600 milliseconds to answer, and user 2 takes 100.

// src/app/app.ts
import { Component, signal } from '@angular/core';

const NAMES: Record<number, string> = { 1: 'Ana', 2: 'Ben' };

function fetchName(id: number): Promise<string> {
  const delay = id === 1 ? 600 : 100;
  return new Promise((resolve) => setTimeout(() => resolve(NAMES[id]), delay));
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="show(1)">User 1</button>
    <button (click)="show(2)">User 2</button>
    <p>User {{ id() }}: {{ name() }}</p>
  `,
})
export class App {
  protected readonly id = signal(0);
  protected readonly name = signal('none');

  protected async show(id: number) {
    this.id.set(id);
    this.name.set('Loading...');
    this.name.set(await fetchName(id));
  }
}

Record<number, string> is a TypeScript type for an object whose keys are numbers and whose values are strings.

Before you read on, guess. Click User 1, then straight away User 2. What does the page say a second later?

At first it looks right. The page shows:

User 1User 2
User 2: Ben

Then, a moment later, it shows:

User 1User 2
User 2: Ana

User 2 is Ben, but the page says Ana. Both calls to show were waiting at the same time. User 2’s answer came first, and user 1’s slow answer came last and overwrote it. (The two buttons show as User 1User 2 because buttons sit on one line, and the page text runs them together.)

This bug is called a race: the result depends on which answer finishes first. It’s easy to miss, because on a fast network the answers usually arrive in order. Part 15’s store had the same hole. You could fix it by hand: remember which id you asked for last, and ignore any other answer. Angular has a tool that does it for you.

resource(): a signal that loads its own value

Here’s the same page with resource:

// src/app/app.ts
import { Component, resource, signal } from '@angular/core';

const NAMES: Record<number, string> = { 1: 'Ana', 2: 'Ben' };

function fetchName(id: number, abortSignal: AbortSignal): Promise<string> {
  console.log(`loading user ${id}`);
  const delay = id === 1 ? 600 : 100;
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve(NAMES[id]), delay);
    abortSignal.addEventListener('abort', () => {
      console.log(`user ${id} aborted`);
      clearTimeout(timer);
      reject(abortSignal.reason);
    });
  });
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="id.set(1)">User 1</button>
    <button (click)="id.set(2)">User 2</button>
    <p>Status: {{ name.status() }}</p>
    <p>User {{ id() }}: {{ name.value() }}</p>
  `,
})
export class App {
  protected readonly id = signal<number | undefined>(undefined);
  protected readonly name = resource({
    params: () => this.id(),
    loader: ({ params, abortSignal }) => fetchName(params, abortSignal),
  });
}

resource comes from @angular/core. You give it an object with two functions:

  • params says what to load. It reads signals, like a computed. Here it returns the selected id. Whenever its result changes, the resource loads again.
  • loader says how to load it. It gets an object with the current params and an abortSignal, and it returns a Promise of the value. ({ params, abortSignal }) => ... picks those two properties out of the object, so we can use them by name.

The resource then gives you signals to read: value() is the loaded value, and status() says what the resource is doing right now.

When the page loads, id is undefined. The page shows:

User 1User 2
Status: idle
User :

idle means “nothing to load”. When params returns undefined, the resource doesn’t call the loader at all. We’ll use that on purpose later.

Click User 1. The page shows:

User 1User 2
Status: loading
User 1:

Now click User 2 straight away, and wait. This time the page ends up right:

User 1User 2
Status: resolved
User 2: Ben

The console tells us what happened:

loading user 1
user 1 aborted
loading user 2

When id changed to 2, the resource no longer wanted user 1. It fired the abort signal for that load, and then it called the loader again with 2.

What abortSignal is

An AbortSignal is a standard browser object. It answers one question: “has someone cancelled this?” It fires an abort event when they have. The resource gives every call to the loader its own signal, and it fires that signal when the load is no longer wanted: when the params change, when you call reload(), set or update while a load is still running, or when the component is destroyed.

Our fake server listens for that event, stops its timer and rejects the Promise. The browser’s fetch does the same thing for real requests: pass it { signal: abortSignal }, and the browser cancels the request. We’ll do that in the next section.

What if a loader ignores the signal? The resource still throws away a result from an old request, so the page still shows Ben. Exercise 3 checks that. The old request just runs to the end for nothing. Passing the signal on lets it stop early.

Watching a param change

This animation follows the clicks above. The dashed blue arrow means “reads”: the resource reads id() in its params function.

signal resource loader calls id: 1 id: 2 User 2 status: loading status: resolved value: undefined value: Ben load user 1 aborted load user 2 answered: Ben id 1, user 1 loading, value undefined id 2, the user 1 load is aborted user 2 loading, status still loading, value undefined status resolved, value Ben, the screen updates The resource reads id() and calls the loader for user 1 Click User 2: id changes, so the old load's abortSignal fires The resource calls the loader again, with params 2 User 2 arrives: status and value change together

A new param cancels the load that’s still running, then starts a new one.

Here are those steps in words, in case the animation doesn’t play for you:

  1. id holds 1. The resource read id() in its params function, and it called the loader for user 1. While that runs, status() is loading and value() is undefined.
  2. You click User 2, and id becomes 2. The resource sees its params changed. It fires the abort signal of the user 1 load, which logs user 1 aborted.
  3. The resource calls the loader again, with params set to 2. The status is still loading.
  4. Ben arrives. The resource sets the value and the status together, and the screen updates. Any answer from the user 1 load would have been thrown away.

The status signals

A resource has more than value(). Here’s a page that shows most of them at once. Its loader counts how often it runs, so you can tell one load from the next.

// src/app/app.ts
import { Component, resource, signal } from '@angular/core';

let calls = 0;

function loadName(fail: boolean): Promise<string> {
  calls++;
  const n = calls;
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (fail) reject(new Error('Server is down'));
      else resolve(`Ana (load ${n})`);
    }, 300);
  });
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="name.reload()">Reload</button>
    <button (click)="name.set('Bea')">Rename</button>
    <button (click)="fail.set(true)">Break it</button>
    <p>status: {{ name.status() }}, isLoading: {{ name.isLoading() }}</p>
    @if (name.hasValue()) {
      <p>Value: {{ name.value() }}</p>
    } @else if (name.error()) {
      <p>Error: {{ name.error()?.message }}</p>
    }
  `,
})
export class App {
  protected readonly fail = signal(false);
  protected readonly name = resource({
    params: () => this.fail(),
    loader: ({ params }) => loadName(params),
  });
}

The page starts loading at once:

ReloadRenameBreak it
status: loading, isLoading: true

When the first load finishes, it shows:

ReloadRenameBreak it
status: resolved, isLoading: false
Value: Ana (load 1)

Click Reload. While the second load runs, the page shows:

ReloadRenameBreak it
status: reloading, isLoading: true
Value: Ana (load 1)

and then:

ReloadRenameBreak it
status: resolved, isLoading: false
Value: Ana (load 2)

reload() runs the loader again with the same params. Notice the difference from a param change. A reload keeps the old value on screen while it works, and its status is reloading. A new param means the old value belongs to something else, so the value goes back to undefined and the status is loading.

Click Rename. The page shows:

ReloadRenameBreak it
status: local, isLoading: false
Value: Bea

set and update work on a resource just as they do on a signal. They change the value here in the browser, without loading anything, and the status becomes local. That’s handy after you’ve saved a change to the server and already know the new value. The next load replaces it.

Click Break it. The params change to true, the loader rejects, and the page shows:

ReloadRenameBreak it
status: error, isLoading: false
Error: Server is down

So there are six statuses, and in Angular 22.3 each one is a plain string:

status() What’s going on value()
'idle' params returned undefined, so nothing loads undefined (or the default)
'loading' loading for new params undefined (or the default)
'reloading' loading again after reload() the old value
'resolved' the loader finished the loaded value
'local' you called set or update the value you set
'error' the loader threw or rejected throws an error

Three shortcuts sit next to status():

  • isLoading() is true while the status is loading or reloading.
  • error() is the error from the loader, or undefined. It’s an Error object, so error()?.message is its text. ?. means “if this isn’t undefined, read .message“.
  • hasValue() is true when there’s a value you can safely read.

That last line of the table matters. In the error status, reading value() throws. That’s why the template checks hasValue() before it reads value(). The second worked example shows what happens if you don’t.

Loading a file with fetch

So far our “server” was a Promise. Let’s load real JSON files. Put two files in your project’s public/ folder. Angular serves everything in public/ at the root of the site, so the app can fetch /user-1.json.

{ "id": 1, "name": "Ana Silva", "email": "ana@example.com" }
{ "id": 2, "name": "Ben Okafor", "email": "ben@example.com" }

There’s no user-9.json. We’ll ask for it anyway.

// src/app/app.ts
import { Component, resource, signal } from '@angular/core';

interface User {
  id: number;
  name: string;
  email: string;
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="id.set(1)">User 1</button>
    <button (click)="id.set(2)">User 2</button>
    <button (click)="id.set(9)">User 9</button>
    @if (user.hasValue()) {
      <p>{{ user.value().name }}, {{ user.value().email }}</p>
    } @else if (user.error()) {
      <p>Couldn't load: {{ user.error()?.message }}</p>
    } @else if (user.isLoading()) {
      <p>Loading...</p>
    } @else {
      <p>Pick a user.</p>
    }
  `,
})
export class App {
  protected readonly id = signal<number | undefined>(undefined);
  protected readonly user = resource({
    params: () => this.id(),
    loader: async ({ params, abortSignal }) => {
      const response = await fetch(`/user-${params}.json`, { signal: abortSignal });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return (await response.json()) as User;
    },
  });
}

The loader is an async function (Part 15 explains async and await), so it returns a Promise. It does three things:

  • fetch(url, { signal: abortSignal }) asks the browser for the file and hands it the abort signal. If the params change mid-request, the browser cancels the request.
  • fetch doesn’t fail on a 404. It gives back a response with ok set to false. So we check response.ok and throw. A loader that throws puts the resource in the error status.
  • response.json() reads the body as JSON. as User tells TypeScript what shape to expect. It’s a promise to the compiler, not a check; httpResource‘s parse option, below, is where a real check goes.

When the page loads, nothing is selected, so the resource is idle and nothing is fetched:

User 1User 2User 9
Pick a user.

Click User 1:

User 1User 2User 9
Ana Silva, ana@example.com

Click User 9:

User 1User 2User 9
Couldn't load: HTTP 404

The browser’s console also has a red line, Failed to load resource: the server responded with a status of 404 (Not Found). The browser prints that for any failed request. It’s not an Angular error.

Returning undefined to skip a load

The @else branch, “Pick a user.”, only shows while params returns undefined. That’s the rule for skipping: return undefined from params, and the resource goes idle and calls nothing. Use it whenever there’s nothing to ask for yet: no id picked, an empty search box, a user who isn’t logged in. It’s simpler than an if inside the loader, and the loader never has to deal with a missing value. TypeScript knows this too. Inside the loader, params is a number, not number | undefined.

defaultValue: never undefined

While a resource is idle or loading, value() is undefined. For a list, that’s a nuisance: every .length needs a check. defaultValue gives the resource a value to use instead:

// src/app/app.ts
import { Component, resource, signal } from '@angular/core';

function loadTags(): Promise<string[]> {
  return new Promise((resolve) => setTimeout(() => resolve(['news', 'sport']), 300));
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="show.set(true)">Show tags</button>
    <p>{{ tags.status() }}: {{ tags.value().length }} tags</p>
  `,
})
export class App {
  protected readonly show = signal<true | undefined>(undefined);
  protected readonly tags = resource({
    params: () => this.show(),
    loader: () => loadTags(),
    defaultValue: [],
  });
}

The template reads tags.value().length with no check, and it builds. With defaultValue: [], the type of value() is string[], not string[] | undefined. Before the click, the page shows:

Show tags
idle: 0 tags

Click Show tags. While it loads, the page shows:

Show tags
loading: 0 tags

and then:

Show tags
resolved: 2 tags

Keep in mind that the empty list is a stand-in. “0 tags” while loading looks the same as a real answer of zero tags. If that difference matters to your user, show isLoading() too. Also, hasValue() is true whenever the value isn’t undefined and there’s no error, so with a default it’s true even while the resource is idle, as the first run above shows.

httpResource: the same thing through HttpClient

Part 18 used HttpClient to make requests, and interceptors to change every request in one place. resource with fetch skips all of that: fetch knows nothing about Angular. httpResource, from @angular/common/http, is a resource that loads through HttpClient, so your interceptors run for it.

You give it a function that returns the URL. Like params, it reads signals, and it loads again when they change. It parses the body as JSON for you, and an HTTP error such as a 404 puts it in the error status without any ok check.

To show that it goes through HttpClient, this app.config.ts adds an interceptor that logs every request:

// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { HttpInterceptorFn, provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';

const logInterceptor: HttpInterceptorFn = (req, next) => {
  console.log(`${req.method} ${req.url}`);
  return next(req);
};

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes),
    provideHttpClient(withInterceptors([logInterceptor])),
  ],
};
{ "id": 1, "name": "Ana Silva", "email": "ana@example.com" }
{ "id": 2, "name": "Ben Okafor", "email": "ben@example.com" }
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';

interface User {
  id: number;
  name: string;
  email: string;
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="id.set(2)">User 2</button>
    @if (user.hasValue()) {
      <p>{{ user.value().name }} ({{ user.statusCode() }})</p>
    }
  `,
})
export class App {
  protected readonly id = signal(1);
  protected readonly user = httpResource<User>(() => `/user-${this.id()}.json`);
}

httpResource<User> says what the JSON holds. Like as User, TypeScript takes your word for it. Besides the usual signals, an httpResource has statusCode() and headers() from the HTTP response.

The page loads user 1 at once. Click User 2. The page shows:

User 2
Ben Okafor (200)

and the interceptor logged both requests:

GET /user-1.json
GET /user-2.json

In Angular 22.3, HttpClient is available in every app without setup. When we tried httpResource without provideHttpClient, it loaded fine. You add provideHttpClient(...) when you want to configure it, as here, to register interceptors.

parse: check what came back

The server can send anything. parse is a function that gets the raw JSON (typed unknown) and returns the value the resource should hold. It’s the place to check the shape, or to turn the data into what your component wants. If parse throws, the resource goes to error, just like a failed request.

{ "id": 1, "name": "Ana Silva", "email": "ana@example.com" }
{ "id": 2, "fullName": "Ben Okafor" }
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';

interface User {
  id: number;
  name: string;
}

function toUser(raw: unknown): User {
  const data = raw as Partial<User>;
  if (typeof data.id !== 'number' || typeof data.name !== 'string') {
    throw new Error('The server sent a user without a name');
  }
  return { id: data.id, name: data.name };
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="id.set(2)">User 2</button>
    @if (user.hasValue()) {
      <p>{{ user.value().name }}</p>
    } @else if (user.error()) {
      <p>{{ user.error()?.message }}</p>
    }
  `,
})
export class App {
  protected readonly id = signal(1);
  protected readonly user = httpResource(() => `/user-${this.id()}.json`, { parse: toUser });
}

Partial<User> is User with every property optional, which is honest about data we haven’t checked yet. We don’t write httpResource<User> here: TypeScript works out the type from what toUser returns.

The page shows Ana Silva. Click User 2, whose file has fullName instead of name. The page shows:

User 2
The server sent a user without a name

Without parse, the page would have shown an empty name and carried on. With it, bad data fails loudly, in one place. Libraries such as Zod build these checks from a description of the shape; parse works with them too.

Worked example: a user card that loads by input

Here’s a more realistic shape. A UserCard component takes a user id as an input (Part 5) and loads that user itself. The parent only picks the id. This is also how a page component reads a route parameter as an input (Part 16) and loads what it names.

{ "id": 1, "name": "Ana Silva", "email": "ana@example.com" }
{ "id": 2, "name": "Ben Okafor", "email": "ben@example.com" }
// src/app/user-card.ts
import { Component, input } from '@angular/core';
import { httpResource } from '@angular/common/http';

interface User {
  id: number;
  name: string;
  email: string;
}

@Component({
  selector: 'app-user-card',
  template: `
    @if (user.hasValue()) {
      <h2>{{ user.value().name }}</h2>
      <p>{{ user.value().email }}</p>
    } @else if (user.error()) {
      <p>Couldn't load user {{ userId() }} ({{ user.statusCode() }}).</p>
      <button (click)="user.reload()">Try again</button>
    } @else {
      <p>Loading user {{ userId() }}...</p>
    }
  `,
})
export class UserCard {
  readonly userId = input.required<number>();
  protected readonly user = httpResource<User>(() => `/user-${this.userId()}.json`);
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { UserCard } from './user-card';

@Component({
  selector: 'app-root',
  imports: [UserCard],
  template: `
    <button (click)="id.set(1)">Ana</button>
    <button (click)="id.set(2)">Ben</button>
    <button (click)="id.set(3)">Someone new</button>
    <app-user-card [userId]="id()" />
  `,
})
export class App {
  protected readonly id = signal(1);
}

Inputs are signals, so the URL function reads this.userId() like any other signal. When the parent passes a new id, the URL changes and the card loads again. The error branch shows statusCode() rather than error()?.message: an HttpClient error message includes the full address of the request, which is more than a user needs to see.

The page loads Ana. Click Ben, and the page shows:

AnaBenSomeone new
Ben Okafor
ben@example.com

There’s no file for user 3. Click Someone new:

AnaBenSomeone new
Couldn't load user 3 (404).
Try again

As before, the browser logs the 404. Try again calls reload(). Here it fails again, since the file still doesn’t exist, but on a flaky network it’s often all the user needs.

Worked example: reading value() during an error

Here’s a slip that’s easy to make. This page reads user.value() with no hasValue() check. It uses resource with a fake loader that fails for user 9.

// src/app/app.ts
import { Component, resource, signal } from '@angular/core';

function loadName(id: number): Promise<string> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id === 9) reject(new Error('No user 9'));
      else resolve('Ana');
    }, 100);
  });
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="id.set(9)">User 9</button>
    <p>Status: {{ name.status() }}</p>
    <p>Name: {{ name.value() }}</p>
  `,
})
export class App {
  protected readonly id = signal(1);
  protected readonly name = resource({
    params: () => this.id(),
    loader: ({ params }) => loadName(params),
  });
}

It builds, and it shows Ana. Click User 9 and wait. The page shows:

User 9
Status: error
Name:

The status line updated, but the name is blank, and the console has a red error:

ERROR ResourceValueError: Resource is currently in an error state (see Error.cause for details): No user 9
    at ResourceImpl...
    at App_Template ...

Read it piece by piece:

  • ResourceValueError is the kind of error. Angular threw it because something read value() while the resource was in the error status.
  • No user 9 at the end is the loader’s own error, the one that made the resource fail. “See Error.cause” means the original error is kept on the new one, as its cause property.
  • at App_Template is the important line. App_Template is the function Angular compiled from App‘s template. So it was the template that read value(), not your class code.

The fix is to check before reading, as we did earlier:

// src/app/app.ts
import { Component, resource, signal } from '@angular/core';

function loadName(id: number): Promise<string> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id === 9) reject(new Error('No user 9'));
      else resolve('Ana');
    }, 100);
  });
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="id.set(9)">User 9</button>
    <p>Status: {{ name.status() }}</p>
    @if (name.hasValue()) {
      <p>Name: {{ name.value() }}</p>
    } @else if (name.error()) {
      <p>Error: {{ name.error()?.message }}</p>
    }
  `,
})
export class App {
  protected readonly id = signal(1);
  protected readonly name = resource({
    params: () => this.id(),
    loader: ({ params }) => loadName(params),
  });
}

Click User 9 and wait. The page shows:

User 9
Status: error
Error: No user 9

and the console is clean.

hasValue() also helps the compiler. Without defaultValue, httpResource<User> holds User | undefined, so reading .name straight off value() doesn’t build:

// src/app/app.ts
import { Component } from '@angular/core';
import { httpResource } from '@angular/common/http';

interface User {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  template: `<p>{{ user.value().name }}</p>`,
})
export class App {
  protected readonly user = httpResource<User>(() => '/user-1.json');
}
✘ [ERROR] TS2532: Object is possibly 'undefined'. [plugin angular-compiler]
      12 │   template: `<p>{{ user.value().name }}</p>`,

Object is possibly 'undefined' points at user.value(). Inside @if (user.hasValue()), TypeScript knows the value isn’t undefined, and the same line builds. That’s what we did in every example above. So one check fixes both problems: the build error for undefined, and the runtime error for error.

In older code

Before resources, a component loaded data in ngOnInit (Part 10) and stored it in a field:

ngOnInit() {
  this.http.get<User>(`/users/${this.id}`).subscribe((user) => (this.user = user));
}

subscribe is the RxJS method from Part 18; Part 20 covers RxJS properly. Loading, error and cancelling were all hand-written, often with an RxJS operator called switchMap, which drops an old request when a new one starts. You’ll also meet resource code written for Angular 19, the first version with resource (it was experimental until Angular 22 made it stable). That code used request where we write params, and it compared the status with an enum, ResourceStatus.Loading. In 22.3, ResourceStatus is only a TypeScript type for the six strings.

Best practices

  • Load data that depends on signals with a resource. Put what to load in params and how in loader. The resource tracks status, errors and stale answers, which replaces a hand-written loading flag, error field and “is this still the latest request?” check.
  • Use httpResource for HTTP requests. It goes through HttpClient, so your interceptors run for it, and it handles JSON and HTTP errors. Keep resource for loaders that aren’t HTTP, or that combine several calls.
  • Pass abortSignal on. Give it to fetch ({ signal: abortSignal }) or listen for its abort event. The resource ignores stale answers anyway; passing the signal also stops the work.
  • Return undefined from params when there’s nothing to load. The resource goes idle and the loader never sees a missing value. It replaces an if at the top of every loader.
  • Check hasValue() before you read value(). It satisfies the compiler and avoids ResourceValueError in the error status. Use defaultValue when a stand-in, like an empty list, is good enough.
  • Use a resource for reading only. A params change aborts the running load, and you don’t want that to happen to a save. Send changes with HttpClient from a method, then set or reload the resource.

Tips and traps

  • Reading value() without a check. It builds whenever the type allows it, for example with a defaultValue, or when you just print it in double curly braces, which accept undefined. Then it throws ResourceValueError from the template as soon as a load fails. Wrap it in @if (x.hasValue()).
  • Expecting fetch to fail on a 404. It doesn’t: you get a response with ok: false, and the loader carries on and reads the error page as if it were your data. You get a confusing JSON error, or worse, wrong data. Check response.ok and throw, or use httpResource, which does it for you.
  • Testing status() === 'loading' to show a spinner. A reload has the status reloading, so the spinner never shows for it. Use isLoading(), which covers both.
  • A params function that reads a signal by accident. Everything params reads is a reason to load again when it changes, as with a computed. Read only what the request needs.
  • Expecting set to save anything. set and update change the value in the browser only. The status turns local, and the next load replaces your value. Save to the server separately.
  • Following a blog post’s request: option. That’s Angular 19’s name. In 22.3 the build fails with TS2769, No overload matches this call, because request isn’t a known option, and the loader’s ({ request }) fails with TS2339, Property 'request' does not exist on type 'ResourceLoaderParams<unknown>'. Use params, and check the installed types when a post disagrees.

A resource turns “what to load” into a signal, and it always shows the answer to the latest question.

Exercises

Exercise 1. Here’s a page that loads a user for whatever id you type, using the JSON files from this part. Paste it, then clear the box. It asks the server for /user-.json, and you get a 404. Change it so that it loads nothing while the box is empty, and shows “Type an id.” instead.

{ "id": 1, "name": "Ana Silva", "email": "ana@example.com" }
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';

interface User {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  template: `
    <input #box placeholder="User id" value="1" (input)="id.set(box.value)" />
    @if (user.hasValue()) {
      <p>{{ user.value().name }}</p>
    } @else if (user.error()) {
      <p>Not found</p>
    }
  `,
})
export class App {
  protected readonly id = signal('1');
  protected readonly user = httpResource<User>(() => `/user-${this.id()}.json`);
}
Not found

Exercise 2. Write a page that loads a post from public/post.json, { "title": "Hello", "likes": 3 }, with httpResource, and shows Hello: 3 likes and a Like button. Each click should add one like on the page, without loading anything. After two clicks the page shows Hello: 5 likes. What is the status after a click?

Exercise 3. Take the resource example from “resource(): a signal that loads its own value” and delete the abortSignal.addEventListener(...) call, so the loader ignores the signal. Add a console.log inside the timer to see when each fake request finishes. Click User 1, then User 2, and wait. What does the page show, and what does the console show?

Answers

1. Return undefined from the URL function when the id is empty. The resource goes idle, and the template’s last branch shows the hint:

{ "id": 1, "name": "Ana Silva", "email": "ana@example.com" }
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';

interface User {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  template: `
    <input #box placeholder="User id" value="1" (input)="id.set(box.value)" />
    @if (user.hasValue()) {
      <p>{{ user.value().name }}</p>
    } @else if (user.error()) {
      <p>Not found</p>
    } @else if (user.status() === 'idle') {
      <p>Type an id.</p>
    }
  `,
})
export class App {
  protected readonly id = signal('1');
  protected readonly user = httpResource<User>(() =>
    this.id() ? `/user-${this.id()}.json` : undefined,
  );
}

The page starts with Ana Silva. Clear the box, and it shows:

Type an id.

No request is made, so there’s no 404 in the console.

2. Put the file in public/:

{ "title": "Hello", "likes": 3 }

Then use update on the resource, with a new object as in Part 3:

// src/app/app.ts
import { Component } from '@angular/core';
import { httpResource } from '@angular/common/http';

interface Post {
  title: string;
  likes: number;
}

@Component({
  selector: 'app-root',
  template: `
    @if (post.hasValue()) {
      <p>{{ post.value().title }}: {{ post.value().likes }} likes</p>
      <button (click)="like()">Like</button>
    }
    <p>Status: {{ post.status() }}</p>
  `,
})
export class App {
  protected readonly post = httpResource<Post>(() => '/post.json');

  protected like() {
    this.post.update((p) => (p ? { ...p, likes: p.likes + 1 } : p));
  }
}

update‘s function gets Post | undefined, because that’s the resource’s type, so it checks p first. Click Like twice. The page shows:

Hello: 5 likes
Like
Status: local

The status is local: the value was set here, not loaded. In a real app you’d also send the like to the server.

3. The page still ends on Ben. The resource ignores the answer from the old load, whether or not the loader listens for the abort. But the old request isn’t stopped, so it still finishes:

// src/app/app.ts
import { Component, resource, signal } from '@angular/core';

const NAMES: Record<number, string> = { 1: 'Ana', 2: 'Ben' };

function fetchName(id: number): Promise<string> {
  console.log(`loading user ${id}`);
  const delay = id === 1 ? 600 : 100;
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`user ${id} finished`);
      resolve(NAMES[id]);
    }, delay);
  });
}

@Component({
  selector: 'app-root',
  template: `
    <button (click)="id.set(1)">User 1</button>
    <button (click)="id.set(2)">User 2</button>
    <p>Status: {{ name.status() }}</p>
    <p>User {{ id() }}: {{ name.value() }}</p>
  `,
})
export class App {
  protected readonly id = signal<number | undefined>(undefined);
  protected readonly name = resource({
    params: () => this.id(),
    loader: ({ params }) => fetchName(params),
  });
}

Click User 1, then User 2, and wait. The page shows:

User 1User 2
Status: resolved
User 2: Ben

and the console shows:

loading user 1
loading user 2
user 2 finished
user 1 finished

user 1 finished comes last, and the page ignores it. With a real request, that’s a download nobody uses. Passing abortSignal to fetch, or using httpResource, cancels it.

What’s next

httpResource runs on HttpClient, and HttpClient runs on RxJS Observables. In Part 20, we’ll meet Observables properly and move between them and signals with toSignal and toObservable.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.