Sub topic 7
Injecting services with inject()
This chapter assumes you know TypeScript, Angular services and dependency injection, basic HttpClient use, and the RxJS operators pipe and tap. You should also have seen a functional interceptor and how withInterceptors registers it.
Why interceptors need inject()
A functional interceptor is a plain function, not a class. It has no constructor, so you can't ask Angular to pass a service in as a constructor parameter. Instead, you call inject() from @angular/core. It returns the instance of a service from the current injector.
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);
};Here inject(AuthService) runs each time a request reaches this interceptor. The service itself is usually a singleton, so you get the same instance every time. Only the lookup repeats.
The injection context
inject() only works inside an injection context. This is a period of time when Angular is running your code with an active injector. Angular runs the body of an interceptor function inside such a context, so inject() is valid at the top level of the function.
The context ends when the function returns. Callbacks that run later, such as the function you pass to tap or catchError, run outside it. Calling inject() there throws a runtime error (NG0203).
Get services first, use them later
The safe pattern is to call inject() at the top of the interceptor, store the results in constants, and use those constants inside later callbacks. The closure keeps the service reference alive.
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
export const redirectOn403Interceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 403) {
router.navigate(['/forbidden']);
}
return throwError(() => error);
}),
);
};The broken version calls inject(Router) inside catchError. It compiles, but it fails at run time when the first error arrives.
Which services can you inject
An interceptor registered through provideHttpClient uses the application's environment injector. You can inject anything provided there, including services marked providedIn: 'root', Router, and tokens you provide yourself. Component-scoped providers are not available, because interceptors are not tied to any component.
Avoiding a circular dependency
If a service you inject itself uses HttpClient, you can create a loop. For example, AuthService.getToken() that calls HttpClient would send its request back through the same interceptor, which would call getToken() again. Keep the services that interceptors depend on free of HTTP calls on the path that the interceptor uses. Reading a token from memory or storage is fine.
| Where you call `inject()` | Works? |
|---|---|
| Top level of the interceptor function | Yes |
| Inside `tap` or `catchError` callbacks | No, throws NG0203 |
| Inside a `setTimeout` callback | No |
| Outside the function, at module level | No |
Exercise
An interceptor calls inject(NotificationService) inside a catchError callback and throws NG0203 on the first failed request. How do you fix it?
Show answer
Move const notifications = inject(NotificationService); to the top of the interceptor function, before next(req) is called, and use the notifications constant inside the catchError callback. The top of the function runs in the injection context, but the callback runs later, outside it.