Sub topic 3
Your first httpResource
This chapter assumes you know TypeScript, Angular components and templates, and signals (signal, computed, reading a signal in a template). It also assumes you know basic HTTP: methods, query parameters and status codes. By the end you will have a working httpResource that loads data from a URL and shows it in a template. You will also know what Angular does when you create one.
What httpResource gives you
httpResource is a function from @angular/common/http. You give it a request description, and it returns a resource object. The resource sends the request through HttpClient and exposes the outcome as signals. You don't subscribe to anything, and you don't write loading or error flags yourself.
import { httpResource } from '@angular/common/http';
const todo = httpResource<Todo>(() => '/api/todos/1');The first argument is a request function. It returns a URL string, a request object, or undefined. This chapter uses only the URL string. Request objects and undefined get their own chapters.
The type argument (<Todo>) tells TypeScript the shape of value(). It is a type assertion, not a check. If the server returns a different shape, TypeScript will not notice at runtime. The parsing chapter covers validation.
Step 1: provide HttpClient
httpResource uses HttpClient internally, so the application must provide it. If you skip this step, creating the resource fails with a missing-provider error (NullInjectorError) for HttpClient. Add provideHttpClient() once in the application config:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};Pass this config to bootstrapApplication(AppComponent, appConfig). Any interceptors you register here also apply to httpResource requests. A later chapter covers that.
Step 2: declare the resource
Here is a complete component that loads one user. It uses a fixed URL, so it sends exactly one request.
import { Component } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-card',
template: `
@if (user.isLoading()) {
<p>Loading…</p>
}
@if (user.error()) {
<p>Could not load the user.</p>
}
<h2>{{ user.value()?.name }}</h2>
`,
})
export class UserCardComponent {
user = httpResource<User>(() => '/api/users/1');
}Four things about this code are worth noting.
- The resource is a field initializer.
httpResourcemust run in an injection context, because it injectsHttpClientand theInjectorit needs for its internal effect. Field initializers and constructors of components, directives and services qualify. - There is no
ngOnInitcall. The resource starts working when it is created. You don't trigger it. - The template reads signals.
user.isLoading(),user.error()anduser.value()are signal reads, so Angular re-renders the template when they change. value()is typedUser | undefined. Before the response arrives,value()isundefined, so the template uses?..
What happens when you create it
The request does not go out inside the httpResource(...) call itself. The sequence is:
- The component is constructed and the resource is created. Its status is
loadingonce the request starts, andvalue()isundefineduntil then. - Angular runs the request function inside a reactive context and records which signals it reads. A fixed string reads none.
- Angular builds an
HttpRequestand sends it throughHttpClient, including your interceptors. - When the response arrives,
value()is set to the parsed JSON body. If the request fails,error()is set instead.
The request goes out through HttpClient, so it behaves like any other HttpClient call. It sends cookies according to your configuration, and a base URL you prepend in an interceptor applies to it too. A relative URL such as /api/users/1 resolves against the page's origin.
What the resource object offers
The returned object has more than the three signals in the template above. These are the members you will use first:
| Member | What it returns |
|---|---|
| `value()` | The parsed body, or `undefined` before a response |
| `hasValue()` | `true` when `value()` holds data |
| `isLoading()` | `true` while a request is in flight |
| `error()` | The error from a failed request, otherwise `undefined` |
| `status()` | One of `idle`, `loading`, `reloading`, `resolved`, `error`, `local` |
| `headers()` | The response headers, once a response arrives |
| `statusCode()` | The HTTP status code of the latest response |
| `reload()` | Repeats the current request |
The next chapter goes through value, status and error in detail. For now it is enough to know that all of them are signals, so you can use them in computed values or effects.
import { Component, computed } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-greeting',
template: `<p>{{ greeting() }}</p>`,
})
export class GreetingComponent {
user = httpResource<User>(() => '/api/users/1');
greeting = computed(() =>
this.user.hasValue() ? `Hello, ${this.user.value()?.name}` : 'Hello, stranger',
);
}greeting recomputes whenever the resource's value changes, with no manual wiring. This is the main benefit of resources being signals.
Creating a resource outside an injection context
Sometimes you need to create a resource later, for example inside a method called from a click handler. Calling httpResource there throws, because there is no injection context. Pass an injector in the options argument:
import { Component, Injector, inject } from '@angular/core';
import { httpResource, HttpResourceRef } from '@angular/common/http';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-lazy-user',
template: `
<button (click)="load()">Load</button>
<p>{{ user?.value()?.name }}</p>
`,
})
export class LazyUserComponent {
private injector = inject(Injector);
user?: HttpResourceRef<User | undefined>;
load() {
this.user = httpResource<User>(() => '/api/users/1', {
injector: this.injector,
});
}
}This pattern is rare. In most cases, one resource declared as a field is the better design, and the request function controls when it fires (a later chapter shows how).
Common errors
NullInjectorError: No provider for HttpClient. You forgotprovideHttpClient()in the application config.httpResourcethrows about injection context. You called it from a regular method or an async callback. Move it to a field initializer or passinjector.- The template shows nothing and no error appears. The resource is still loading or the body is empty. Check
status()and the browser's Network tab. value()has the wrong shape at runtime. The generic type is not enforced. Validate withparse, covered later.- A plain
fetch-styleResponseis expected.httpResourcereturns parsed JSON by default, not aResponse. Use thetext,blobandarrayBuffervariants for other body types.
Where this chapter stops
Your resource sends one request for a fixed URL. Making the URL depend on a signal, so that a new request fires when the signal changes, is the next step. Request objects (method, params, headers, body) and write operations come later and have their own chapters.
Exercise
A teammate writes httpResource<User>(() => '/api/users/1') in a component, and the browser console shows NullInjectorError: No provider for HttpClient. What is missing, where does it go, and why does it matter for httpResource specifically?
Show answer
The application config needs provideHttpClient() in its providers array (for example in appConfig passed to bootstrapApplication). httpResource sends its requests through HttpClient internally, so without that provider the resource cannot be created.
Exercise
You declare user = httpResource<User>(() => '/api/users/1') as a component field. Name the type of user.value() before the response arrives, and give one way to read the name in a template without a runtime error.
Show answer
value() is User | undefined, and it is undefined before the response arrives. Use optional chaining, as in {{ user.value()?.name }}, or wrap the output in a check such as user.hasValue().