Sub topic 12
How httpResource builds on HttpClient and interceptors
This chapter assumes you can write Angular components, use signals, and have declared a basic httpResource (earlier chapters). You should also know what an HTTP interceptor is in general. Here you will see how httpResource relates to HttpClient, why interceptors apply to it automatically, and where its own options connect to the HTTP layer.
httpResource is a layer over HttpClient
httpResource does not send requests itself. Each time its request function produces a new value, it builds an HttpRequest and hands it to HttpClient. The resource subscribes to the resulting observable and writes the outcome into its signals: value, status, error, headers, statusCode and progress.
This has three practical consequences:
- Setup is shared. You need
provideHttpClient(). Without it, creating the resource fails with aNullInjectorErrorforHttpClient. - Behavior is shared. Interceptors, the configured backend (XHR or fetch), XSRF protection and the testing backend all apply to resource requests as they do to
HttpClientcalls. - Cancellation uses unsubscribe. When a newer request replaces an older one, the resource unsubscribes from the old observable.
HttpClientthen aborts the in-flight network request.
Registering interceptors
Interceptors are registered where you provide HttpClient, using withInterceptors. This is the same configuration you would use for HttpClient alone.
import { ApplicationConfig, Injectable, inject, signal } from '@angular/core';
import {
HttpInterceptorFn,
provideHttpClient,
withFetch,
withInterceptors,
} from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class AuthService {
readonly token = signal<string | null>('demo-token');
}
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).token();
if (!token) {
return next(req);
}
return next(
req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }),
);
};
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
],
};Every httpResource in the application now sends the Authorization header. You do not touch the resource declarations. This is the main reason to prefer httpResource over a bare fetch call: cross-cutting concerns such as authentication, logging, base URLs and error reporting stay in one place.
withFetch() is optional. It switches the backend from XMLHttpRequest to the Fetch API. The resource behaves the same either way, but fetch is the usual choice with server-side rendering.
When the interceptor runs
An interceptor runs each time the resource sends a request. That includes the first load, a reload after a signal change, and a call to reload(). An interceptor that reads a signal, as authInterceptor does, reads the current value at that moment.
Reading that signal inside the interceptor does not make the resource reactive to it. Only signals read inside the request function trigger new requests. If the token changes and the data should be fetched again, call reload() yourself, or put the token into a signal that the request function reads.
Passing per-request information with HttpContext
An interceptor often needs to treat some requests differently. The request object accepts a context property of type HttpContext. Define a token, read it in the interceptor, and set it on the resource.
import { Component, signal } from '@angular/core';
import {
HttpContext,
HttpContextToken,
HttpInterceptorFn,
httpResource,
} from '@angular/common/http';
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);
export const optionalAuthInterceptor: HttpInterceptorFn = (req, next) => {
if (req.context.get(SKIP_AUTH)) {
return next(req);
}
return next(req.clone({ setHeaders: { Authorization: 'Bearer demo-token' } }));
};
interface Country {
code: string;
name: string;
}
@Component({
selector: 'app-countries',
template: `
@for (c of countries.value(); track c.code) {
<p>{{ c.name }}</p>
}
`,
})
export class CountriesComponent {
readonly region = signal('europe');
countries = httpResource<Country[]>(
() => ({
url: '/public/countries',
params: { region: this.region() },
context: new HttpContext().set(SKIP_AUTH, true),
}),
{ defaultValue: [] },
);
}Here the public endpoint skips the token. Register optionalAuthInterceptor with withInterceptors as shown earlier. Note that the request function returns a new HttpContext each time it runs. That is fine, because a new request is built whenever its signal dependencies change.
Other request options that map to HttpClient
The request object is a thin description of an HttpRequest. These properties pass straight through:
| Property | Effect |
|---|---|
| `url`, `method`, `body` | Basic request line and payload |
| `params`, `headers` | Query parameters and headers |
| `context` | `HttpContext` read by interceptors |
| `withCredentials` | Sends cookies on cross-site requests |
| `reportProgress` | Fills the resource's `progress()` signal |
| `transferCache` | Controls reuse of server-rendered responses on the client |
The resource also exposes response metadata that HttpClient calls normally hide behind observe: 'response'. statusCode() returns the numeric status and headers() returns the HttpHeaders. Both are signals, so you can read them in a template.
Interceptors that change the outcome
Because the resource only sees what comes out of the interceptor chain, interceptors can reshape results.
- Retry. An interceptor that applies the RxJS
retryoperator makes the resource retry transparently. Restrict it to idempotent methods such as GET. - Error mapping. An interceptor can catch an
HttpErrorResponseand rethrow a friendlier error. The resource'serror()signal then holds your error. - Caching. An interceptor can return
of(new HttpResponse(...))for a cached URL. The resource shows a normal loaded state without a network call.
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, retry, throwError } from 'rxjs';
export const resilientGetInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method !== 'GET') {
return next(req);
}
return next(req).pipe(
retry({ count: 2, delay: 500 }),
catchError((err: HttpErrorResponse) =>
throwError(() => new Error(`GET ${req.url} failed with ${err.status}`)),
),
);
};With this in place, a failing GET is attempted three times in total (one try and two retries) before the resource enters its error state. Keep retries small. A user who changes a signal during the retry delay cancels the whole chain, because the resource unsubscribes from the outer observable.
Injection context
HttpClient is obtained with inject(), so httpResource must be created in an injection context. Field initializers in a component or service qualify, as in the examples above. If you create a resource later, for example inside an event handler, pass the injector option:
import { Component, Injector, inject } from '@angular/core';
import { httpResource } from '@angular/common/http';
@Component({
selector: 'app-lazy',
template: `<button (click)="start()">Load</button>`,
})
export class LazyComponent {
private injector = inject(Injector);
data?: ReturnType<typeof httpResource.text>;
start() {
this.data = httpResource.text(() => '/assets/notes.txt', {
injector: this.injector,
});
}
}Without the injector, start() fails because there is no active injection context.
Consequences for testing
Because the resource goes through HttpClient, you test it with the standard tools: provideHttpClient() plus provideHttpClientTesting(), and HttpTestingController to match and flush requests. Interceptors registered in the test providers run too, so assert on the headers they add. The testing chapter covers this in detail.
Common errors
- No
provideHttpClient(). Symptom: aNullInjectorErrorforHttpClientwhen the component is created. - Interceptors registered in the wrong place. Providing
HttpClienta second time in a lazy route's providers creates a separate client without your interceptors. - Expecting reactivity from interceptor reads. See the warning above.
- Creating a resource outside an injection context. Pass
injector. - Retrying non-idempotent methods. Resource requests can be writes if you set
method: 'POST', but retrying them can duplicate side effects.
Exercise
A resource's request function returns /api/orders. An interceptor adds an X-Tenant header read from a tenant signal. The user switches tenants, but the order list does not refresh. Why, and what are two ways to fix it?
Show answer
The interceptor runs outside the request function, so reading tenant there does not make the resource reactive to it. The resource only refetches when signals read inside the request function change. Fix it either by calling reload() on the resource after the tenant changes, or by reading tenant() inside the request function, for example in a query parameter or a context value, so a change triggers a new request.
Exercise
You create httpResource.text(() => '/assets/notes.txt') inside a button click handler and get an error about the injection context. What is the cause and the fix?
Show answer
httpResource calls inject(HttpClient) internally, and a click handler has no active injection context. Capture an Injector with inject(Injector) in the constructor or a field initializer, then pass it as the injector option when creating the resource.