← Back to Angular, page 4

angular-0073 · Medium mid

What is httpResource, how does it differ from HttpClient used with toSignal, and what is its status?

httpResource is a signal-based wrapper over HttpClient. You give it a function that returns the request, and it fetches again when the signals read in that function change, exposing value, status, error, isLoading and reload as signals. It is experimental in Angular 19 and 20 and is meant for reads, not writes.

Full answer

httpResource is built on resource and HttpClient. It uses the same pipeline, including interceptors, so authentication and error handling still apply.

ts
courses = httpResource<Course[]>(() => ({
  url: '/api/courses',
  params: { q: this.query() },
}));

How it works:

  • The function is reactive. When this.query() changes, a new request is sent and the previous one is cancelled.
  • If the function returns undefined, the resource stays idle and sends nothing. This handles "no id yet".
  • Result signals: value(), status() (idle, loading, reloading, resolved, error, local), error(), isLoading(), headers(), and hasValue(). reload() runs the request again.
  • Variants for other response types: httpResource.text(), httpResource.blob(), and httpResource.arrayBuffer().
  • parse validates and converts the response. The generic type is not checked at runtime, so a parse function (written by hand or with a schema library such as Zod) is the safe approach.
  • The value can be set locally with set() and update(), which is handy for optimistic updates.

Compared with toSignal(http.get(...)): the old way needs toObservable, switchMap, a manual loading flag, and an error flag. httpResource provides all of it for the common case. For debounce, retries with backoff, polling, or merging streams, RxJS is still better, and you can combine both.

Status: httpResource and resource are experimental in Angular 19 and 20, so the API can change in minor versions. Use them with that in mind, and keep usage in a few wrapper services so a later change is cheap.

Important: it is for reading data. Use HttpClient directly for POST, PUT, and DELETE.

typescript
import { httpResource } from '@angular/common/http';
import { Component, signal } from '@angular/core';

interface Course {
  id: number;
  title: string;
}

function parseCourses(raw: unknown): Course[] {
  if (!Array.isArray(raw)) {
    throw new Error('Expected a list of courses');
  }
  return raw.map((item) => {
    const row = item as Partial<Course>;
    if (typeof row.id !== 'number' || typeof row.title !== 'string') {
      throw new Error('Invalid course');
    }
    return { id: row.id, title: row.title };
  });
}

@Component({
  selector: 'app-course-finder',
  template: `
    <input #box placeholder="Search" (input)="query.set(box.value)" />
    <button (click)="courses.reload()">Reload</button>

    @if (courses.isLoading()) {
      <p>Loading...</p>
    } @else if (courses.error(); as err) {
      <p role="alert">Failed: {{ err.message }}</p>
    } @else if (courses.hasValue()) {
      <ul>
        @for (c of courses.value(); track c.id) {
          <li>{{ c.title }}</li>
        } @empty {
          <li>No courses</li>
        }
      </ul>
    }
  `,
})
export class CourseFinderComponent {
  readonly query = signal('');

  readonly courses = httpResource<Course[]>(
    () => ({
      url: '/api/courses',
      params: { q: this.query() },
    }),
    { parse: parseCourses, defaultValue: [] },
  );
}

Angular 20.3 (experimental API, may change). It needs `provideHttpClient()`. The `parse` function checks the shape before the data reaches the template.

Key points

  • Reactive request function. A signal change cancels the old request and starts a new one.
  • Provides `value`, `status`, `error`, `isLoading`, `reload`, and local `set`.
  • Use `parse` to validate the response. The generic type is only a hint.
  • Experimental in Angular 19 and 20. Reads only.

Common mistakes

  • Using `httpResource` to send a POST or DELETE.
  • Reading `value()` while the resource is in an error state, which throws.
  • Trusting the generic type as validation.

Follow-ups

  • How does it differ from `resource` with `fetch`?
  • How would you debounce the query that drives an `httpResource`?
  • How do interceptors apply to it?

Tips

  • State the experimental status in your first sentence.
  • Compare it with the toObservable plus switchMap plus toSignal pattern.
  • Mention `parse` for runtime validation.

Evaluation rubric

  • Explains reactive requests and cancellation.
  • Lists state signals and variants.
  • States status and limits honestly.