Angular 11 is causing confusion by incorrectly applying the Http interceptor to sibling modules

Here is the structure of my modules:

https://i.sstatic.net/zO9dE.png

The HTTP interceptor I provided in core.module.ts is affecting the HTTP client in the translation.module.ts. This is how my core module is set up:

@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 {}

And this is the code for my translation module:

@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',
        reRenderOnLangChange: true,
        prodMode: environment.production
      })
    },
    { provide: TRANSLOCO_LOADER, useClass: TranslationLoader }
  ]
})
export class TranslationModule {}

Both modules are included in my app module:

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

The issue arises when the translation module tries to load JSON files with incorrect URLs due to the interference of the BaseUrl interceptor. If anyone has a solution to this problem, please share your thoughts.

I am looking for a solution that does not involve conditionally applying the base URL within the interceptor or checking for specific headers.

Answer №1

Your approach to providing the TranslationLoader loader appears unconventional. Both providing it in the module and setting the providedIn value to forRoot in the Injectable decorator can lead to confusion with the Dependency Injector. This could potentially cause issues if someone tries to inject it without the TRANSLOCO_LOADER token - as it might not know which HttpClientModule to utilize.

I suggest choosing a single method for providing the loader - either remove it from providers or eliminate the providedIn parameter from the decorator and rely on injection tokens only for injection.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tapping into the space outside the MUI Modal Component in a React application

Can Modal Component in MUI be used with a chat bot? When the modal is open, can users interact with buttons and inputs outside of it? How can this be implemented? I want to be able to click outside the modal without closing it. Modal open={open} onClo ...

Error due to PlatformLocation's location dependency issue

My AppComponent relies on Location (from angular2/router) as a dependency. Within the AppComponent, I am using Location.path(). However, when running my Jasmine test, I encountered an error. Can you help me identify the issue with my Jasmine test and guide ...

Setting up BrowserSync to work with an index.html file located within the src directory

Up until now, I have been using this project structure: project/ | +---src/ | | | +---app/ | +---node_modules/ | +---index.html +---package.json | ... It has worked well for me so far, but I have noticed that the common approach is to place index.htm ...

Troubleshooting ng module not found error when deploying Typescript + Angular app on Azure App Service using Azure DevOps pipeline

My Typescript and Angular application runs perfectly when tested locally. Now, I'm in the process of setting up a deployment pipeline using Azure DevOps to build and release it to an App Service running on Linux (Node.js web app). Although the pipel ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

Struggling with installing Angular CLI, can anyone provide guidance on resolving the issue?

When trying to install Angular CLI on my laptop for practicing Angular, I encountered an error that caused it to freeze. Despite attempting various solutions, the problem persists. What could be the possible solution? S F:\talent_angular> npm insta ...

"Authentication guard does not sit idle while waiting for the observable

My issue involves the auth guard service constructor(private _auth: AuthService, private _router: Router) { } canActivate() { if(this._auth.isLoggedIn()){ return true; } else { this._router.navigate(['/login']); ret ...

What is the best way to set up JSData with cookie-based sessions and CSRF headers?

In order to properly configure my JSData settings, I must include instructions for passing information related to cookie-based session authentication and CSRF headers. ...

Getting the date from an XHR header in Angular2: A step-by-step guide

Is it possible to retrieve a date from XHR Header Response? https://i.sstatic.net/ErMMh.jpg I attempted to include '{observe: 'response'}' as options constructor(private http: HttpClient) { } getAllTemps() { return this. ...

Exploring the power of spyOn within nested functions for AngularFirestore with Jasmine

Attempting to simulate AngularFirestore: beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: AngularFirestore, useValue: { collection: () => ({ doc: () => ({ s ...

Are we on the correct path for breaking down code using react JS?

As I work on creating reusable table components, each column comes with its own set of functionalities, which results in dealing with numerous components. To streamline the process, I have been separating every component piece into individual files and ex ...

Investigating TypeScript Bugs in Visual Studio Code

As I navigate through various sources, I notice that there is a plethora of information available on older versions of VSCode (v1.16.1 - the most recent version at the time of writing) or deprecated attributes in the launch.json file. I have experimented ...

Storing AngularJS route components in the cache for optimal performance (keep-alive)

I'm looking for a way to cache the state of a component A so that it doesn't re-render every time I navigate away and back to it. This component also makes a slow API call in its constructor. I want to maintain this initial state throughout the u ...

Delete an essential attribute from an entity

I am trying to remove a required property called hash from an object, but I keep encountering TypeScript or ESLint errors. All the properties of the interface are mandatory, and I do not want to make all properties optional using Partial. Here is the inte ...

Authentication using SPA RSA 2048 encryption technology

For my current project involving Angular SPA development, the customer has requested the use of RSA 2048 for authentication. I'm uncertain about how the authentication token will be generated. My understanding is that the token should be created on th ...

Angular is not programmed to automatically reflect updates made to my string array

let signalRServerEndPoint = 'https://localhost:44338'; this.connection = $.hubConnection(signalRServerEndPoint); this.proxy = this.connection.createHubProxy('MessagesHub'); this.proxy.on("ReceiveMessage", (message) => { ...

What is the best way to transfer props between components using typescript?

I have a unique button component that I need to include in another component. The button type and interface I am using are as follows: type IButton = { className?: string, onClick?: MouseEventHandler; children: React.ReactNode; props: IButt ...

Angular CLI - Monitoring libraries for updates to trigger rebuilding of dependent applications

Currently, I am in the process of creating an Angular Library with the usual setup where I have my main library project and another project where I utilize the output of the built library. My goal is to set up a system that automatically monitors changes ...

Is it possible to enhance the GamepadAPI's functionality?

I've been working on enhancing the built-in GamepadAPI by adding custom controller code. With TypeScript, I created a basic function to trigger a "gamepadconnected" event. // emulate gamepadconnected event function dispatchGamepadConnectedEv ...

Angular material table

I'm having an issue with deleting a record from a table that I created using Angular Material- Even after successfully deleting a record, the view does not refresh. Here is the HTML code snippet - <ng-container matColumnDef="delete"> ...