Injecting AuthService to the Interceptor's constructor was giving me this error:
Uncaught Error: Provider parse errors: Cannot instantiate cyclic
dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in
NgModule AppModule in ./AppModule@-1:-1
So instead of injecting it to the constructor, I used Injector
of @angular/core
and it worked fine. I am storing the token in localStorage
and using basic auth. I need to set
Authorization: 'Bearer token_string'
Here is how I have 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
Here you can implement the whole logic to get the header or only the token. Here in my case, I am only calling this to get the JWT token string.
/**
* 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 under @NgModule
in providers:
array.
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
//, other providers
]