I'm using Angular 10 and I have a few services and one interceptor that is causing:
ERROR Error: Uncaught (in promise): Error: Cannot instantiate cyclic dependency! InjectionToken HTTP_INTERCEPTORS Error: Cannot instantiate cyclic dependency! InjectionToken HTTP_INTERCEPTORS
app.module.ts
@NgModule({
declarations: [
AppComponent,
DashboardComponent,
],
imports: [
AuthModule, // <= A custom module
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true},
],
bootstrap: [AppComponent]
})
export class AppModule {
}
Interceptor
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(
private responseHandler: HttpResponseHandlerService
) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((err: HttpErrorResponse, source) =>
this.responseHandler.onCatch(err, source) // Catching all the errors here.
)
);
}
}
HttpResponseHandlerService
@Injectable({
providedIn: 'root',
})
export class HttpResponseHandlerService {
constructor(
// This is causing the error!
private authService: AuthService
) {
}
public onCatch(response: HttpErrorResponse, source: Observable<any>): Observable<any> {
return throwError(response);
}
}
AuthModule
@NgModule({
declarations: [
LoginComponent
],
imports: [
SharedModule, // <= A shared module
AuthRoutingModule
],
providers: [
AuthService
]
})
export class AuthModule {
}
AuthService
@Injectable()
export class AuthService extends HttpService {
constructor(
// Maybe this is causing the cyclic dependency ?
http: HttpClient
) {
super(http);
}
login(username: string, password: string) {
}
}
SharedModule
@NgModule({
declarations: [],
imports: [
CommonModule,
],
exports: [
FormsModule,
ReactiveFormsModule,
],
providers: [
HttpService // <= A custom service to handle HTTP requests
]
})
export class SharedModule {
}
HttpService
@Injectable()
export class HttpService {
constructor(
private http: HttpClient
) {
}
get<T>(options: any): Observable<T> {
}
}
I have tried everything and I cannot get rid off the issue. I don't understand the origin of the error.
My goal is to fix the cyclic dependency issue correctly.