Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 74 ยท Signals and Reactivity

linkedSignal, resource and httpResource

Learn linkedSignal for state that resets when its source changes, and resource() and httpResource() for loading async data with status, value, error and cancellation.

Plain signal() and computed() cover most state, but two common situations need more. The first is state that is derived but still editable: a selected option that should reset when the list of options changes, yet still lets the user pick something else. The second is asynchronous data: a value that arrives later from a server and depends on other signals, such as "the user with this id".

Angular has a signal-shaped answer for each. linkedSignal() is a writable signal whose value is recomputed whenever a source changes. resource() runs an async loader whenever its parameters change and exposes the result as signals for value, status and error. httpResource() is resource() specialized for HTTP requests. This lesson explains all three and then rebuilds the ideas with runnable stand-ins.

Real versus stand-in. The typescript and html blocks are real Angular and read-only, because the site cannot run the Angular compiler. The runnable examples use hand-written stand-ins for linkedSignal and resource. They are simplified: real Angular has more statuses, schedules effects differently and handles many edge cases. At the time of writing resource() and httpResource() were still marked experimental in Angular's documentation, so check the current API reference before relying on exact option names.

linkedSignal: derived state you can still write

Suppose a size picker shows the sizes a product comes in. When you move to another product, the old selection may no longer exist. A computed() would reset correctly but could never be assigned; a signal() could be assigned but would never reset. linkedSignal() does both.

TypeScript
import { Component, linkedSignal, signal } from '@angular/core';

@Component({
  selector: 'app-size-picker',
  template: `
    @for (size of sizes(); track size) {
      <button [class.active]="size === selected()" (click)="selected.set(size)">{{ size }}</button>
    }
  `,
})
export class SizePickerComponent {
  readonly sizes = signal(['S', 'M', 'L']);

  // Short form: always follows the first size, but can be set by the user.
  readonly selected = linkedSignal(() => this.sizes()[0]);
}

The short form takes one function. Each time any signal it reads changes, the value is recomputed and the user's earlier choice is thrown away. When you want a smarter rule, use the long form with a source and a computation. The computation receives the new source value and the previous state, so you can keep the old choice when it is still valid.

TypeScript
readonly selected = linkedSignal<string[], string>({
  source: this.sizes,
  computation: (sizes, previous) =>
    previous && sizes.includes(previous.value) ? previous.value : sizes[0],
});

Here previous holds the earlier source and value, and is undefined on the first run. The signal returned is a WritableSignal, so selected.set('L') and selected.update(...) work like on any other signal.

The stand-in below implements the long form. Watch which changes keep the user's pick and which reset it.

TypeScript A linkedSignal stand-in: resettable selection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each line is logged by an effect that depends on both signals. After the pick of L, a new list that still contains L keeps it, and a list without it falls back to the first entry. This "keep if still valid, otherwise reset" rule is the typical reason to reach for linkedSignal.

resource: async data as signals

resource() ties an async function to signals. You give it two things: a params function that reads signals and returns the request description, and a loader that does the asynchronous work. Whenever the params change, Angular cancels the previous load (through an AbortSignal it passes to your loader) and starts a new one.

TypeScript
import { Component, computed, resource, signal } from '@angular/core';

interface User { id: number; name: string }

@Component({
  selector: 'app-user-card',
  template: `
    <button (click)="id.set(id() + 1)">Next user</button>

    @if (user.isLoading()) {
      <p>Loading...</p>
    } @else if (user.error()) {
      <p>Something went wrong. <button (click)="user.reload()">Retry</button></p>
    } @else if (user.hasValue()) {
      <p>{{ user.value()?.name }}</p>
    }
  `,
})
export class UserCardComponent {
  readonly id = signal(1);

  readonly user = resource({
    params: () => ({ id: this.id() }),
    loader: async ({ params, abortSignal }) => {
      const response = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return (await response.json()) as User;
    },
  });
}

The loader must return a Promise; fetch is the usual tool, and passing abortSignal lets the browser drop the abandoned request. Anything the loader reads from signals is not tracked, so put everything that should trigger a reload into params. If params returns undefined, the resource stays idle and does not load, which is handy for "wait until the user chose something".

The returned resource ref gives you signals and methods:

Member Meaning
value() The loaded value, or undefined while there is none
status() One of idle, loading, reloading, resolved, error, local
error() The thrown error, if the last load failed
isLoading() / hasValue() Convenient booleans for templates
reload() Run the loader again with the same params
set() / update() Write a value locally, for instance an optimistic update
stateDiagram-v2
  [*] --> idle
  idle --> loading: params defined
  loading --> resolved: loader succeeded
  loading --> error: loader threw
  resolved --> loading: params changed
  resolved --> reloading: reload()
  reloading --> resolved: loader succeeded
  error --> loading: params changed

The lifecycle of a resource. reloading is like loading but keeps the previous value on screen.

Because the state is plain signals, the template and any computed() stay in sync without manual subscriptions. Compare this with the older style from RxJS Essentials of holding a loading flag, an error field and a subscription that you must clean up yourself.

httpResource: resource for HTTP

Most loaders are just HTTP GETs, so httpResource() skips the boilerplate. You pass a function returning a URL (or a request object), and it uses Angular's HttpClient under the hood. That means interceptors, provideHttpClient() and test mocks work as usual, and the response is parsed as JSON by default.

TypeScript
import { httpResource } from '@angular/common/http';

readonly id = signal(1);

readonly user = httpResource<User>(() => `/api/users/${this.id()}`);

Reading this.id() inside the function is what makes the request depend on the signal. Return undefined to hold the request back. The result has the same value(), status(), error() and reload() members as resource(). Reach for plain resource() when you are not using HttpClient, for example with a third-party SDK or fetch for a special endpoint. HttpClient: Requests and Responses covers the underlying client.

A resource stand-in with cancellation

This stand-in shows the mechanism: an effect watches the params, aborts the previous request, starts a new one, and ignores answers from requests that were cancelled. The fake loader uses timers instead of a network, with user 1 deliberately slower than user 2.

TypeScript A resource stand-in with a fake loader and cancellation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You see the status move through idle, loading and resolved, one cancellation line when the id changes while user 1 is still loading, an error for the missing user, and a return to idle. Without the aborted check the slow answer for user 1 would arrive after user 2's and overwrite it: this "stale response" bug is exactly what the abort handling in a real resource() prevents.

When to use which

  • computed() when the value is purely derived and never assigned.
  • linkedSignal() when it is derived but the user can override it, and the override should reset when the source changes.
  • resource() or httpResource() when the value comes from an async source and depends on signals. Keep fire-and-forget actions such as saving a form separate: resources are for reading data that depends on state, not for POST requests that change things.
  • Plain Observables with HttpClient still make sense for streams, retries and complex composition, see RxJS Operators You Need.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What problem does linkedSignal solve that computed cannot?

    computed() values are read-only. linkedSignal() is a writable signal that recomputes whenever its source changes, so it suits a selection that resets with its options.
  2. 2. In the long form of linkedSignal, what does the previous argument of computation contain?

    It lets you keep the earlier value when it is still valid, for example if (previous && list.includes(previous.value)).
  3. 3. Why must everything that should trigger a reload go into the params function of resource()?

    Angular watches params to decide when to load again. The loader runs untracked, so reading a signal there does not retrigger it.
  4. 4. What happens to the previous request when a resource's params change while it is still loading?

    Cancelling avoids the stale response race, where a slow old answer would arrive after a newer one and overwrite it.
  5. 5. When should you prefer httpResource over resource?

    httpResource is resource specialized for HTTP through HttpClient. Mutating requests such as POST are better done in regular service methods.

Summary

  • linkedSignal() is a writable signal whose value is recomputed when its source changes; the long form can keep the previous value when it is still valid.
  • resource() combines a params function with an async loader, cancels outdated loads and exposes value, status, error, isLoading, hasValue and reload.
  • Only params is tracked; the loader is not, and returning undefined from params keeps the resource idle.
  • httpResource() is resource() for HTTP through HttpClient, with the URL function as its dependency list.
  • Both resource APIs were still experimental when this was written, so check the current docs for exact names.

Next: Change Detection, OnPush and Zoneless.