Sub topic 1
Fetching data with httpResource in Angular
Prerequisites
This chapter assumes TypeScript fundamentals, Angular components and templates, Angular signals, and basic HTTP concepts such as methods, headers, query parameters, and status codes.
Why resources: async data as signals
An HTTP request is asynchronous: the response arrives later, may fail, and can become outdated. A resource is an Angular object that represents this changing operation.
httpResource connects an HTTP request to Angular signals. Its request can read other signals, and its state is exposed through signals such as value(), error(), status(), and isLoading().
This keeps request state close to the component that displays it. The template can react to loading, success, and failure without manually subscribing to an observable.
Setting up HttpClient
httpResource uses Angular's HttpClient internally. Provide the client in the application configuration:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};Without this provider, Angular cannot create the HTTP resource.
Your first httpResource
Declare a resource with a request function. The function returns the URL or a request object.
import { Component } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user',
template: `
<p>{{ user.value()?.name }}</p>
`,
})
export class UserComponent {
user = httpResource<User>(() => '/api/users/1');
}The generic type, User, describes the successful response. The request starts when the resource becomes active.
Reading value, status, and errors in templates
A resource's signals describe its current state:
value()returns the latest successful value, orundefinedbefore one exists.isLoading()is true while a request is running.error()contains the failure when the request fails.status()identifies the broader resource state.
@Component({
selector: 'app-user',
template: `
@if (user.isLoading()) {
<p>Loading…</p>
} @else if (user.error()) {
<p>Could not load the user.</p>
} @else if (user.value(); as currentUser) {
<p>{{ currentUser.name }}</p>
}
<small>Status: {{ user.status() }}</small>
`,
})
export class UserComponent {
user = httpResource<User>(() => '/api/users/1');
}Exercise
Why does the template call user.value() instead of reading user.value?
Show answer
value is a signal, so value() reads its current value and lets Angular track the dependency.