I’m setting up a JWT interceptor in Angular 18.. I had this set up in Angular 8, although that was a completely different setup using a class which inherits HttpInterceptor. here I am using function injection…
In app.module.ts I have the providers set as such:
providers: [
provideHttpClient(
withInterceptors([jwtInterceptor])
)
],
The jwt.interceptor.ts is as such:
import { Inject, Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHandlerFn } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../_services';
export function jwtInterceptor(request: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
// add auth header with jwt if user is logged in and request is to the api url
const _authenticationService: AuthenticationService = Inject(AuthenticationService) as AuthenticationService;
const _baseUrl: string = Inject('BASE_URL') as string;
const currentUser = JSON.parse(JSON.stringify(_authenticationService.UserValue));
const isLoggedIn = _authenticationService.IsLoggedIn;
const isApiUrl = request.url.indexOf(_baseUrl) == 0;
if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.authData}`
}
});
}
return next(request);
}
now for the things I’m trying to inject:
AuthenticationService (important to note here that injecting base url in the constructor works, also I can inject the AuthenticationService itself into other constructors, just not in this httpInterceptors function):
import { Inject, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { LoginInformation, User } from '../_dataObjects';
@Injectable({ providedIn: 'root' })
export class AuthenticationService {
private _userSubject: BehaviorSubject<User>;
public User: Observable<User>;
constructor(private _router: Router, private http: HttpClient, @Inject('BASE_URL') private _baseUrl: string) {
var username = localStorage.getItem('user') ?? '';
this._userSubject = new BehaviorSubject<User>(username.length > 0 ? JSON.parse(username) : new User());
this.User = this._userSubject.asObservable();
}
...
}
Base url is defined in main.ts providers as such:
const providers = [
{ provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];