Skip to content
jshacks.dev
Frameworks

Load data with resource in Angular

Fetch async data tied to a signal with Angular's experimental resource API, and read its value, status and error without writing the plumbing.

1 min read
Summarize in AI

Loading data when an id changes usually means an effect, a loading flag and manual cancellation. resource ties an async loader to signals.

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

@Component({
  selector: 'app-user',
  template: `
    <button (click)="id.set(id() + 1)">Next</button>
    @if (user.isLoading()) {
      <p>Loading…</p>
    } @else if (user.error()) {
      <p>Could not load the user</p>
    } @else {
      <p>{{ user.value()?.name }}</p>
    }
  `,
})
export class UserComponent {
  id = signal(1);

  user = resource({
    params: () => ({ id: this.id() }),
    loader: async ({ params, abortSignal }) => {
      const res = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
      if (!res.ok) throw new Error('Request failed');
      return res.json();
    },
  });
}
Text
Loading…
Ada                (id 1)
Loading…           (after Next)
Lin                (id 2)

When params changes, the previous request is aborted through abortSignal and the loader runs again. The params and loader option names are those of Angular 20 and later, where the feature is still experimental, so its API may change. See Async reactivity with resources.

For plain HTTP calls through HttpClient, httpResource is the more convenient sibling. Treat both as experimental before relying on them in a production application.

Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.