Sub topic 7
Injecting services with inject()
A functional interceptor is a plain function, so it has no constructor to receive dependencies through. It gets services with the inject() function from @angular/core. This chapter covers where that call is allowed, what you can inject, and the mistakes that cause runtime errors. It assumes you can write a basic functional interceptor with HttpInterceptorFn and know what a root-provided service is. It also assumes you know basic RxJS: pipe, tap, switchMap.
Why interceptors use inject()
A class-based interceptor declares its dependencies in a constructor, and Angular builds the instance. A functional interceptor has no instance. The signature is only (req, next) => Observable<HttpEvent<unknown>>, and you cannot add a third parameter for a service.
Angular solves this by running the function inside an injection context. This is a window of time in which inject() can find the current injector. Inside that window, a call like inject(AuthService) returns the service instance.
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).getToken();
if (!token) {
return next(req);
}
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` },
});
return next(authReq);
};inject(AuthService) is the first statement in the body. That placement matters, as the next section explains.
The injection context
The injection context exists only while Angular is synchronously running your function. HttpClient calls each interceptor as the request moves down the chain, and it does so inside the application's environment injector. When your function returns, the context closes.
The function returns an Observable before most of its work happens. Code inside tap, map, switchMap or catchError callbacks runs later, when the response arrives. By then the context is gone, so inject() throws.
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { tap } from 'rxjs';
import { AuthService } from './auth.service';
// Wrong: inject() runs inside a callback, after the context has closed.
export const brokenInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
tap(() => {
const auth = inject(AuthService); // throws NG0203
auth.markActivity();
}),
);
};
// Right: inject first, then use the reference in the callback.
export const fixedInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
return next(req).pipe(
tap(() => auth.markActivity()),
);
};The error you see for the broken version is NG0203: inject() must be called from an injection context. The fix is always the same. Call inject() at the top level of the interceptor function and keep the result in a const. Callbacks can then use that reference through closure.
What you can inject
The interceptor runs in the environment injector, the injector built from your application-level providers. It can inject anything that injector can see.
| Source of the provider | Can the interceptor inject it? |
|---|---|
| `providedIn: 'root'` service | Yes |
| Provider in `bootstrapApplication` or `ApplicationConfig` | Yes |
| Provider in a lazy route's `providers` array | Yes, but only when the request comes from within that route's injector tree |
| `InjectionToken` with a root factory or a registered value | Yes |
| Provider in a component's `providers` or `viewProviders` | No |
| Directive or element-level providers | No |
The last two rows are a common source of confusion. A component can provide its own copy of a service, but the interceptor does not run in the component's injector. It sees the application-level instance, or fails to find the service if none is registered there.
Injecting a configuration token
inject() is not limited to classes. Any InjectionToken works, which keeps environment-specific values out of the interceptor code.
import { HttpInterceptorFn } from '@angular/common/http';
import { InjectionToken, inject } from '@angular/core';
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');
export const baseUrlInterceptor: HttpInterceptorFn = (req, next) => {
const baseUrl = inject(API_BASE_URL);
if (req.url.startsWith('/api/')) {
return next(req.clone({ url: `${baseUrl}${req.url}` }));
}
return next(req);
};Register the token next to the HTTP providers:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { API_BASE_URL, baseUrlInterceptor } from './app/base-url.interceptor';
bootstrapApplication(AppComponent, {
providers: [
{ provide: API_BASE_URL, useValue: 'https://example.com' },
provideHttpClient(withInterceptors([baseUrlInterceptor])),
],
});A call to http.get('/api/data') now goes to https://example.com/api/data. Requests to other URLs pass through unchanged.
Optional dependencies
inject() accepts an options object. With optional: true it returns null instead of throwing when no provider exists. This suits an interceptor that lives in a shared library and should work in apps that have not registered a particular service.
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { TelemetryService } from './telemetry.service';
export const telemetryInterceptor: HttpInterceptorFn = (req, next) => {
const telemetry = inject(TelemetryService, { optional: true });
telemetry?.recordRequest(req.method, req.urlWithParams);
return next(req);
};The type of telemetry is TelemetryService | null, so TypeScript forces you to handle the missing case.
Injecting per request, not per application
Angular calls the interceptor function again for every request. Each call runs inject() again. This has two consequences.
- It is cheap.
inject()looks up an existing instance. It does not create a new one for root-provided services, so there is no need to cache the result in a module-level variable. - Do not cache it anyway. Storing the service in a variable outside the function (
let auth: AuthService;) breaks testing, because the stale instance survives betweenTestBedsetups. It also breaks apps that create more than one injector.
Circular dependencies and request loops
Two different problems come up when the injected service itself uses HttpClient.
- Cyclic dependency at construction. Class-based interceptors are built when
HttpClientis built. If their constructor injects a service that needsHttpClient, Angular reportsNG0200: Circular dependency. Functional interceptors avoid this, becauseinject()runs at request time, afterHttpClientalready exists. - A request loop at runtime. Suppose
AuthService.refresh()callshttp.post('/auth/refresh', ...)and the interceptor callsrefresh()for some condition. That inner request travels through the same interceptor chain. If the condition is true again, the interceptor triggers another refresh, and the cycle never ends.
You can break the loop in two ways. Skip the interceptor for that request with an HttpContextToken, which a later chapter covers. Or send the request through HttpBackend, which bypasses all interceptors:
import { HttpBackend, HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class RawHttp {
private readonly http = new HttpClient(inject(HttpBackend));
post<T>(url: string, body: unknown) {
return this.http.post<T>(url, body);
}
}Here inject() is used in a field initializer. That is allowed because a field initializer in an injectable class also runs in an injection context while Angular constructs the instance.
Using inject() in tests
Because the interceptor reads its dependencies with inject(), tests supply them by providing replacements. The test in the spine registers { provide: AuthService, useValue: { getToken: () => 'abc' } } and runs a real request through HttpClient. That is usually the best approach, since it exercises the real registration.
To call the interceptor function directly, run it inside a context yourself:
import { HttpRequest, HttpResponse } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { authInterceptor } from './auth.interceptor';
import { AuthService } from './auth.service';
describe('authInterceptor (direct call)', () => {
it('forwards a cloned request with the header', (done) => {
TestBed.configureTestingModule({
providers: [{ provide: AuthService, useValue: { getToken: () => 'abc' } }],
});
const req = new HttpRequest('GET', '/api/data');
const next = (r: HttpRequest<unknown>) => {
expect(r.headers.get('Authorization')).toBe('Bearer abc');
return of(new HttpResponse({ status: 200 }));
};
TestBed.runInInjectionContext(() => {
authInterceptor(req, next).subscribe(() => done());
});
});
});runInInjectionContext opens the same kind of window Angular opens for a real request. Without it, the call to inject() inside the interceptor would throw NG0203.
Summary of rules
- Call
inject()synchronously, at the top of the interceptor function. - Store the result in a
constand use it inside RxJS callbacks. - Expect only application-level providers. Component-level providers are invisible to interceptors.
- Use
{ optional: true }for services that may not be registered. - Watch for services that use
HttpClientinternally, because their requests re-enter the chain.
Exercise
The interceptor below compiles but throws NG0203 at runtime when a response arrives. Explain why, and rewrite it so it works. export const countInterceptor: HttpInterceptorFn = (req, next) => { return next(req).pipe( tap(() => inject(StatsService).increment()), ); };
Show answer
The tap callback runs when the response arrives, after the interceptor function has returned and the injection context has closed, so inject() has no injector to use. Move the call to the top level of the function and use the reference inside the callback:
export const countInterceptor: HttpInterceptorFn = (req, next) => {
const stats = inject(StatsService);
return next(req).pipe(
tap(() => stats.increment()),
);
};
Exercise
A component declares providers: [CartService]. An interceptor calls inject(CartService). Which instance does the interceptor get, and what happens if CartService is not registered anywhere at application level and is not providedIn: 'root'?
Show answer
The interceptor never gets the component's instance, because it runs in the environment injector and cannot see element-level providers. If CartService is provided only in the component, inject(CartService) throws a NullInjectorError. With inject(CartService, { optional: true }) it returns null instead. To share state between the component and the interceptor, provide the service at application level, for example with providedIn: 'root'.
Exercise
AuthService.refresh() uses HttpClient to call /auth/refresh, and your interceptor calls refresh() whenever the stored token is missing. Why can this loop forever, and name two ways to prevent it.
Show answer
The refresh request goes through the same interceptor. The token is still missing, so the interceptor calls refresh() again, which sends another request, and so on. Prevent it by marking the refresh request with an HttpContextToken that the interceptor checks to skip itself, or by sending the refresh request through a client built with HttpBackend, which bypasses all interceptors. Checking the request URL in the interceptor also works but is more fragile.