NGX Translate inside Library throws Circular Dependency error when used in HTTP_INTERCEPTOR

Viewed 741

I have a angular library where I created a LanguageModule defined as follows

@NgModule({
    imports: [
      TranslateModule.forRoot({
        loader: {
          provide: TranslateLoader,
          useFactory: (createTranslateLoader),
          deps: [HttpClient]
        },
      })
    ],
    exports: [TranslateModule]
  })
  export class LanguageModule {
    public constructor(translateSvc: TranslateService, http: HttpClient) {
      translateSvc.onLangChange
        .pipe(
          switchMap((currentLang: LangChangeEvent) => zip(
            of(currentLang),
            http.get(`assets/i18n/${currentLang.lang}.json`),
          ))
        ).subscribe(([currentLang, localizations, syncfusionLocalization]) => {
          translateSvc.setTranslation(translateSvc.currentLang, localizations, true);
          setCulture(currentLang.lang);
        });
  
      translateSvc.use(translateSvc.getDefaultLang());
    }
  }

This allows me to merge library and app localization files.

Inside my app I import the LanguageModule in the main app.module.ts, where I also import my CoreModule, defined as follows:

@NgModule({
    imports: [
      CommonModule,
      HttpClientModule,
      BrowserAnimationsModule,
      ...
    ],
    declarations: [],
    providers: [
        ....
      // Http interceptors
      {
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
      }
    ]
  })
  export class CoreModule {  
    public constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
      if (parentModule) {
        throw new Error('CoreModule has already been loaded. Import CoreModule in the AppModule only.');
      }
    }  
  }

In the AuthInterceptor, if I inject the TranslateService I get the following error: Circular dependency in DI detected for InjectionToken HTTP_INTERCEPTORS.

What am I missing?

2 Answers

Your TranslateService depends on HttpClient, HttpClient depends on HTTP_INTERCEPTORS which include AuthInterceptor.

So when you add TranslateService as a dependency for AuthInterceptor you get a full circle: TranslateService => TranslateLoader => HttpClient => AuthInterceptor => TranslateService.

There is an official guide here https://angular.io/errors/NG0200

Related