Sub topic 2
Setting up HttpClient
httpResource does not send requests itself. It hands them to Angular's HttpClient. If the application has not provided HttpClient, the resource cannot work. This chapter covers how to provide it, which options matter, and what goes wrong when it is missing.
This chapter assumes you know TypeScript, standalone Angular components, and the basics of dependency injection (providers and inject()).
Why the setup step exists
Angular does not register HttpClient by default. Many applications never make HTTP calls, so the HTTP stack is opt-in and can be tree-shaken out of the bundle. You enable it by adding provideHttpClient() to your providers.
httpResource follows the same rule. When you create one, it looks up HttpClient in the injector that is active at that moment. It then sends every request through that client. The practical consequences are:
- The resource uses the same interceptors, XSRF handling, and backend as the rest of your HTTP code.
- The resource must be created in an injection context. The usual places are a field initializer, the constructor, or a function called from one of those.
- If no provider exists, creating the resource fails with a
NullInjectorError.
The minimal setup
In a standalone application, add provideHttpClient() to the providers array of your application config:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};Then pass the config to bootstrapApplication:
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err),
);After this, any component, service, or function running in an injection context can call httpResource(...) or inject(HttpClient).
Features you can add to provideHttpClient
provideHttpClient() accepts feature functions as arguments. Each one switches on an optional behavior. These are the ones you are most likely to meet:
| Feature function | What it does |
|---|---|
| `withFetch()` | Uses the browser `fetch` API instead of `XMLHttpRequest`. |
| `withInterceptors([...])` | Registers functional interceptors that can inspect or change every request and response. |
| `withInterceptorsFromDi()` | Keeps class-based interceptors registered with the `HTTP_INTERCEPTORS` token working. |
| `withXsrfConfiguration({...})` | Customizes the cookie and header names used for XSRF protection. |
| `withJsonpSupport()` | Enables `HttpClient.jsonp()`. Resources do not need it. |
Two of these deserve a closer look.
withFetch
By default, HttpClient uses XMLHttpRequest. withFetch() switches the backend to fetch. Angular recommends it for server-side rendering, because fetch is available in server runtimes. withFetch() does not change how you write an httpResource. The request function, value(), status(), and error() behave the same.
One difference matters for tooling. XMLHttpRequest reports upload progress events and fetch does not, so code that relies on upload progress needs XMLHttpRequest. Plain reads through httpResource are not affected.
withInterceptors
An interceptor is a function that receives the outgoing request and a next handler. It can modify the request before it is sent, and it can observe or transform the response. Because httpResource sends its requests through HttpClient, every interceptor you register applies to resources automatically.
import { ApplicationConfig } from '@angular/core';
import {
HttpInterceptorFn,
provideHttpClient,
withFetch,
withInterceptors,
} from '@angular/common/http';
export const clientHeaderInterceptor: HttpInterceptorFn = (req, next) => {
if (req.url.startsWith('/api/')) {
return next(req.clone({ setHeaders: { 'X-Client': 'web' } }));
}
return next(req);
};
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withFetch(), withInterceptors([clientHeaderInterceptor])),
],
};Interceptors run in the order of the array for the request, and in reverse order for the response. A later chapter covers this in detail. For now, remember that one registration point covers both your resources and your HttpClient calls.
Setting up with NgModules
If your application still uses NgModule, you can pass the same provider in the module's providers:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [provideHttpClient()],
bootstrap: [AppComponent],
})
export class AppModule {}Older code imports HttpClientModule instead. That module is deprecated in favor of provideHttpClient(), so use the function in new code. If you are migrating, note that HttpClientModule registers class-based interceptors from DI automatically, while provideHttpClient() needs withInterceptorsFromDi() to do the same.
Where you provide it matters
The injector that creates the resource decides which HttpClient it gets. This has two effects.
- Root providers are the default choice. Providing in
appConfiggives every component the same client and the same interceptors. - Narrower providers create a separate client. If you call
provideHttpClient()again in a route'sprovidersarray or a component'sproviders, that scope gets its own client with its own interceptors. Resources created inside that scope use the scoped client.
Repeating provideHttpClient() in a child scope is rarely what you want. Interceptors from the parent do not carry over to the child client unless you register them again. If a resource seems to skip an interceptor, check whether a child scope provides a second client.
What a missing provider looks like
If you declare an httpResource without providing HttpClient, creating the component fails. The message depends on your Angular version, but it names HttpClient and says no provider was found. Older versions print NullInjectorError: No provider for HttpClient!. Newer ones report error NG0201.
The fix is always the same: add provideHttpClient() to the providers that cover the failing component.
Injection context
httpResource calls inject(HttpClient) internally, so it follows the same rule as inject(). These are valid places to create one:
import { Component, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';
interface Todo {
id: number;
title: string;
}
@Component({
selector: 'app-todo',
template: `<p>{{ todo.value()?.title }}</p>`,
})
export class TodoComponent {
id = signal(1);
// Valid: a field initializer runs in an injection context.
todo = httpResource<Todo>(() => `/api/todos/${this.id()}`);
}This is not valid: creating a resource inside a click handler or a setTimeout callback. At that point there is no injection context, and Angular throws an error saying that inject() must be called from one. Declare the resource once as a field, and change the signals it reads instead of creating new resources.
If you need to create one in other code, pass an injector in the options object, or wrap the call in runInInjectionContext.
Verifying the setup
A quick check helps catch mistakes before you build real features. Add a throwaway resource to a component and watch the browser's network tab:
- Declare
ping = httpResource.text(() => '/assets/ping.txt');in a component. - Create
ping.txtin your assets folder with any text. - Render
{{ ping.value() }}in the template. - Load the page and confirm one GET request appears.
If the text renders, the provider, the injection context, and the dev server are all working. Remove the check afterward.
Testing setup
Unit tests need their own providers, because TestBed does not read your appConfig. In tests, pair provideHttpClient() with provideHttpClientTesting(). The testing provider replaces the real backend with one you can control, so no real network calls happen. Order matters: put provideHttpClient() first. A later chapter shows how to flush responses and assert on requests.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});Common mistakes
- Forgetting
provideHttpClient()entirely. The component fails with a missing-provider error. - Importing
httpResourcefrom the wrong package. It lives in@angular/common/http, withHttpClient, not in@angular/core. - Providing the client twice in different scopes. Resources in the inner scope silently skip the root interceptors.
- Creating resources outside an injection context. Move the declaration to a field initializer or constructor.
- Registering class-based interceptors without
withInterceptorsFromDi(). They are ignored.
Exercise
A teammate adds data = httpResource<Item[]>(() => '/api/items'); to a component. The page fails on load with an error that no provider was found for HttpClient. What single change fixes it, and where do you make it?
Show answer
Add provideHttpClient() to the providers array of the application config (appConfig), so it is available to the whole app. httpResource injects HttpClient, and Angular does not provide it unless you register it.
Exercise
You registered an auth interceptor with withInterceptors([...]) in appConfig. A resource inside one lazy route does not send the auth header. The route's providers array contains provideHttpClient(). What is the likely cause, and what are two ways to fix it?
Show answer
The route's provideHttpClient() creates a second HttpClient for that scope, and it has no interceptors. Fix it either by removing provideHttpClient() from the route so it uses the root client, or by repeating withInterceptors([...]) in the route's call.
Exercise
Why does creating an httpResource inside a button click handler fail, and what should you do instead?
Show answer
httpResource calls inject(HttpClient), which needs an injection context. A click handler does not run in one. Declare the resource once as a class field (or in the constructor) and let its request function read signals. Then change those signals in the handler.