Encountered an issue when trying to inject AuthService into the Interceptor's constructor, resulting in this error message:
Uncaught Error: Provider parse errors: Cannot instantiate cyclic
dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in
NgModule AppModule in ./AppModule@-1:-1
To resolve the problem, I opted to utilize the Injector
from @angular/core
, which successfully resolved the issue. The token is stored in localStorage
and basic auth is being used. Below is the implementation:
Authorization: 'Bearer token_string'
This is how it was implemented:
token.interceptor.ts
import {Injectable, Injector} from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {AuthService} from './auth.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private injector: Injector) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = this.injector.get(AuthService);
if (auth.getToken()) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${auth.getToken()}`
}
});
}
return next.handle(request);
}
}
getToken function in AuthService
The logic to retrieve the header or just the token can be implemented here. In this case, only the JWT token string is retrieved.
/**
* Get jwt token
* @returns {string}
*/
getToken(): string {
return localStorage.getItem('token');
}
app.module.ts
Import the TokenInterceptor
import {TokenInterceptor} from './pathToTheFile/token.interceptor';
Add the following code snippet under @NgModule
within the providers:
array.
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
//, other providers
]