Sub topic 1
Starting point: HttpClient and provideHttpClient
Prerequisites
This chapter assumes you already know the following:
- TypeScript fundamentals: types, interfaces, arrow functions, and generics.
- Basic Angular concepts: components, services, and dependency injection (DI).
- How to use
HttpClientto make simple GET and POST requests. - Basic RxJS: what an
Observableis, how to callsubscribe, and how to usepipewith operators such astapandcatchError.
You do not need any knowledge of interceptors. This chapter covers the setup that interceptors build on. Later chapters add the interceptors themselves.
Why start here
An HTTP interceptor is a function that Angular's HttpClient calls for every request. If HttpClient is not set up correctly, no interceptor can run. Most "my interceptor does nothing" problems are really setup problems, so it pays to be exact about how HttpClient is provided.
This chapter covers four things:
- What
HttpClientis and what it returns. - How
provideHttpClient()makes it available. - Where interceptors will be attached later, using the same function.
- A small baseline application, so you can see requests flow before any interceptor exists.
What HttpClient is
HttpClient is an Angular service for talking to HTTP backends. It lives in the @angular/common/http package. You inject it into a component or service and call methods such as get, post, put, patch, and delete.
Three properties of HttpClient matter for interceptors:
- Methods return cold Observables. A cold Observable does nothing until someone subscribes. The request is sent when you call
subscribe, or when theasyncpipe does it for you. If you subscribe twice, the request is sent twice. - Responses are typed by you, not checked by Angular.
http.get<User[]>(url)tells TypeScript the body is aUser[]. Angular does not validate this at runtime. - By default you get the body only. The Observable emits the parsed response body. Status codes and headers are hidden unless you pass
observe: 'response'orobserve: 'events'.
The third point is the most relevant one. Under the surface, HttpClient always works with a stream of events (sent, progress, headers, response). The convenience methods filter that stream down to the body. An interceptor sits below this filtering, so it sees the full event stream. A later chapter on responses and events relies on this.
Providing HttpClient with provideHttpClient
In modern Angular, you make HttpClient available by calling provideHttpClient() in the application's providers. This replaces the older HttpClientModule, which you import into an NgModule.
For a standalone application, add it to bootstrapApplication:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [provideHttpClient()],
});If you use app.config.ts, which is the layout ng new generates, the same call goes in the providers array of ApplicationConfig:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};If you inject HttpClient without providing it, Angular throws a NullInjectorError that names HttpClient. The fix is to add provideHttpClient() to the providers.
Features are added as arguments
provideHttpClient() accepts optional arguments called features. Each feature is created by a function whose name starts with with. Features turn on extra behavior in the same HttpClient instance.
| Feature function | What it does |
|---|---|
| `withInterceptors([...])` | Registers functional interceptors. This is the main subject of this tutorial. |
| `withInterceptorsFromDi()` | Allows class-based interceptors registered with `HTTP_INTERCEPTORS`. |
| `withFetch()` | Uses the browser's `fetch` API instead of `XMLHttpRequest`. |
| `withXsrfConfiguration({...})` | Customizes the cookie and header names used for XSRF protection. |
| `withJsonpSupport()` | Enables `HttpClient.jsonp()`. |
Interceptors are not a separate system. They are one of these features. When you write provideHttpClient(withInterceptors([myInterceptor])) in a later chapter, you are using the same function you just saw, with one extra argument.
Provide it once
Call provideHttpClient() once, at the root of the application. This matters because interceptors are attached to the HttpClient instance created by that call.
If you call it a second time in a lazy-loaded route's providers, Angular creates a new child HttpClient in that route's injector. By default, that child instance does not inherit the interceptors of the parent. A request from a service resolved in that route can then skip your interceptors. A later chapter on pitfalls returns to this. For now, the rule is to provide it in one place unless you have a specific reason not to.
The path of a request
Even without interceptors, a request passes through several stages. Interceptors will be added between the first and the last.
Reading the diagram from left to right:
- Your code calls a method such as
http.get('/api/users'). HttpClientbuilds anHttpRequestobject that describes the method, URL, headers, and body.- The request enters the handler chain. Right now the chain has one member: the final handler that performs the network call. Interceptors will be inserted ahead of it.
- The server replies. The response travels back along the same chain as a stream of
HttpEventvalues. HttpClientapplies theobserveandresponseTypeoptions and emits the result to your subscriber.
An interceptor is a function placed in step 3. It can read the request, change it, pass it on, or inspect what comes back.
A baseline application
The following code is a complete small setup that you will extend in later chapters. It has a User interface, a service, and a standalone component that displays the result.
First, the service:
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
private readonly http = inject(HttpClient);
getUsers(): Observable<User[]> {
return this.http.get<User[]>('https://jsonplaceholder.typicode.com/users');
}
}The service uses inject(HttpClient) instead of a constructor parameter. Both styles work. The inject() function is used here because functional interceptors, which you write later, can only get services that way. Using it now makes the later code look familiar.
Next, a component that subscribes through the async pipe:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { UserService } from './user.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [AsyncPipe],
template: `
<h1>Users</h1>
<ul>
@for (user of users$ | async; track user.id) {
<li>{{ user.name }}</li>
}
</ul>
`,
})
export class AppComponent {
readonly users$ = inject(UserService).getUsers();
}Finally, the bootstrap file from earlier:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [provideHttpClient()],
});Run the application and open the browser's network panel. You should see one GET request to /users. Notice what is absent: no Authorization header, no logging, and no error handling beyond whatever the browser does. Each of those is a cross-cutting concern, meaning logic that every request needs and that does not belong to any one service. Interceptors exist to hold that logic in one place.
What goes wrong without interceptors
Imagine the application grows to thirty services. Each one calls http.get or http.post. Now the backend requires a bearer token. Without interceptors you have three options:
- Add the header in every call. This is repetitive, and one forgotten call causes a 401 that is hard to trace.
- Wrap
HttpClientin your own service and force everyone to use it. This works, but it hides the fullHttpClientAPI and relies on team discipline. - Register one interceptor. Every request that goes through
HttpClientpasses through it, whichever service made the call.
The third option is why interceptors exist. The same reasoning applies to logging, timing, error reporting, and retry.
Seeing the event stream yourself
You can observe the lower-level event stream before writing an interceptor. Passing observe: 'events' makes HttpClient emit every event rather than only the body:
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class EventsDemoService {
private readonly http = inject(HttpClient);
getUsersAsEvents(): Observable<HttpEvent<unknown>> {
return this.http.get('https://jsonplaceholder.typicode.com/users', {
observe: 'events',
});
}
}For a plain GET without progress reporting, you typically see two events: a Sent event (type 0) as soon as the request goes out, and a Response event (type 4) when the server replies. These are values of the HttpEventType enum. An interceptor receives this same stream, which is why later chapters check event.type === HttpEventType.Response to find the actual response.
Common setup mistakes
These are the setup errors that most often cause "my interceptor is not running" later.
provideHttpClient()is missing.HttpClientcannot be injected. Angular reports aNullInjectorError.HttpClientModuleandprovideHttpClient()are mixed. Importing the old module in a component orNgModulecan create a secondHttpClientsetup. Pick one approach per injector tree. New code should useprovideHttpClient().provideHttpClient()is called in several places. As described above, a child injector can get its ownHttpClientwithout the root interceptors.- Requests bypass
HttpClient. Calls made withfetch(),XMLHttpRequest, or a third-party library never pass through Angular's chain, so no interceptor sees them. - The Observable is never subscribed to. A cold Observable sends nothing until subscribed. If you see no request in the network panel, check this first.
What comes next
You now have a working HttpClient and know where interceptors attach: as a feature argument to provideHttpClient(). The next chapters build on this in order. They explain what an interceptor does in the request and response chain, why HttpRequest objects are immutable, and how to write your first functional interceptor.
Exercise
A teammate adds an interceptor that logs every request. In the browser, one service's calls are logged, but calls from a service inside a lazy-loaded route are not. The route's providers array contains provideHttpClient(). What is the likely cause, and what is the fix?
Show answer
The route's provideHttpClient() creates a new HttpClient setup in the route's injector. That setup does not inherit the root interceptors by default, so the lazy route's requests skip them. The fix is to remove provideHttpClient() from the route's providers, so the service uses the single root HttpClient, which has the interceptors registered.
Exercise
You call this.http.get<User[]>('/api/users') in a service method but never subscribe to the result, and you do not use the async pipe. Will an interceptor see a request? Explain why.
Show answer
No. HttpClient methods return cold Observables, so no request is sent until something subscribes. With no subscription there is no request, so no interceptor runs.