Robin
Robin

Reputation: 8518

Http interceptor is mistakenly applied to sibling modules in Angular 11

I'm having the following module structure:

diagram

Unfortunately the HTTP interceptor which I provide in core.module.ts is also applied to the HTTP client in the translation.module.ts. My core module looks like this:

@NgModule({
  declarations: [DefaultLayoutComponent],
  providers: [
    { provide: BASE_API_URL, useValue: environment.api },
    { provide: HTTP_INTERCEPTORS, useClass: BaseUrlInterceptor, multi: true }
  ],
  imports: [BrowserModule, BrowserAnimationsModule, RouterModule, HttpClientModule],
  exports: [DefaultLayoutComponent]
})
export class CoreModule {}

My translation module has the following code:

@Injectable({ providedIn: 'root' })
export class TranslationLoader implements TranslocoLoader {
  constructor(private http: HttpClient) {}

  getTranslation(lang: string) {
    return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
  }
}

@NgModule({
  declarations: [],
  imports: [HttpClientModule, TranslocoModule],
  providers: [
    {
      provide: TRANSLOCO_CONFIG,
      useValue: translocoConfig({
        availableLangs: ['en-US', 'de-CH', 'fr-CH', 'it-CH'],
        defaultLang: 'en-US',
        // Remove this option if your application doesn't support changing language in runtime.
        reRenderOnLangChange: true,
        prodMode: environment.production
      })
    },
    { provide: TRANSLOCO_LOADER, useClass: TranslationLoader }
  ]
})
export class TranslationModule {}

Both modules are used in my app module:

@NgModule({
  declarations: [AppComponent],
  imports: [AppRoutingModule, CoreModule, TranslationModule],
  bootstrap: [AppComponent]
})
export class AppModule {}

The translation module loads some JSON files which don't have the correct URL, because the BaseUrl interceptor is applied. Somebody has an idea how to deal with this?

What I don't want is a workaround like only conditionally apply the base url within the interceptor or checking for some custom header.

Upvotes: 0

Views: 387

Answers (1)

Daniel Gimenez
Daniel Gimenez

Reputation: 20609

The way you are providing TranslationLoader loader seems strange. You are both providing it in the module and have the providedIn value set to forRoot in the Injectable decorator. It could be by doing things the way you currently are that it's creating some confusing with the Dependency Injector. I could especially see a problem if somebody injects it without the TRANSLOCO_LOADER token - exactly how it would know which HttpClientModule to use?

So try picking a method and either remove it in providers, or remove the providedIn parameter from the decorator and only inject it using an injection token.

Upvotes: 1

Related Questions