I followed this article from medium to create a http interceptor which lets me add headers to each http call
@Injectable()
export class TokenInterceptor impl
From the article it says:
It should be noted that Angular’s new HttpClient from @angular/common/http is being used here and not the Http class from @angular/http. If we try to make requests with the traditional Httpclass, the interceptor won’t be hit
Please make sure you are using import { HttpClient } from '@angular/common/http';
in the import section.
and then it the constructor use it: constructor(public http: HttpClient) {}
A conventional way to avoid circular dependencies in both AngularJS and Angular is to get another provider instance in-place and not on provider instantiation:
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService, public injector: Injector) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const httpClient = injector.get(HttpClient);
...
}
}
Notice that if the interceptor applies to all HttpClient
requests, it will be applied to the one that is done inside the interceptor itself and likely result in infinite recursion. In order to avoid this the request can be marked to skip the interceptor (e.g. via custom header).