I am receiving the following strange dependency injection behavior when using custom HttpInterceptors in angular 5+.
The following simplified code works fine:
So it turns out that if the service you inject into the Http Interceptor has a dependency on HttpClient
, this leads to a cyclic dependency.
Since my AuthService
was a mix of all different logics (login/out, routing the user, saving/loading tokens, making api calls), I separated the part needed for the interceptors into its own service (just the user credentials & tokens) and now injecting it successfully into the Interceptor.
export class AuthInterceptor implements HttpInterceptor {
constructor(private credentials: CredentialsService) {}
intercept(request: HttpRequest, next: HttpHandler): Observable> {
const token = this.credentials.getToken();
const api_key = this.credentials.getApiKey();
}
}
export class CredentialsService {
token: string;
user: IUser;
constructor(private http: HttpClient) {
this.loadCredentialsFromStorage();
}
}
This seems to work fine. Hope this helps someone.