2

I have the following code:

// config.service.ts
import { Injectable } from "@angular/core";

@Injectable()
export class ConfigService {
  private language: string = "en";
  constructor() {}
  set Language(lang: string) {
    this.language = lang;
  }
  get Language(): string {
    return this.language;
  }
}

// app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule, APP_INITIALIZER } from "@angular/core";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

import { AnalyticsService, CoreModule, CrossDomainService } from "./core";
import { TileModule } from "./tile/tile.module";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, TileModule, CoreModule.forRoot()],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: onModuleInit,
      multi: true,
      deps: [CrossDomainService, AnalyticsService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

export function onModuleInit(
  crossDomainService: CrossDomainService,
  analyticsService: AnalyticsService
) {
  return () => {
    console.log("App Init");
    crossDomainService.init();
    analyticsService.init();
    return new Promise(resolve => resolve(true));
  };
}

//core.module.ts
import { NgModule, ModuleWithProviders } from "@angular/core";
import { CommonModule } from "@angular/common";
import {
  HTTP_INTERCEPTORS,
  HttpClientModule,
  HttpClient
} from "@angular/common/http";

import { HttpRequestInterceptor } from "./http-request.interceptor";
import { ArticleService } from "./article.service";
import { CrossDomainService } from "./cross-domain.service";
import { AnalyticsService } from "./analytics.service";

import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
import { ConfigService } from "../config.service";

export function translateHttpLoaderFactory(http: HttpClient) {
  //return new TranslateHttpLoader(http);
  return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}

@NgModule({
  imports: [
    CommonModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: translateHttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [
    ArticleService,
    CrossDomainService,
    AnalyticsService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpRequestInterceptor,
      multi: true
    }
  ]
})
export class CoreModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: CoreModule,
      providers: [ConfigService]
    };
  }
}

//http-request.interceptor.ts
import { Injectable } from "@angular/core";
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest
} from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import { ConfigService } from "../config.service";

@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
  language: string = "en";
   constructor(private config: ConfigService) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {    
    const request = req.clone({
      setHeaders: { "Accept-Language": this.config.Language }
    });
    console.log(
      `Request header value : ${request.headers.get("Accept-Language")}`
    );

    return next.handle(request);
  }
}

CrossDomainService, in this case is used to get the language from an external system. It is a connector between the application and the external services. enter image description here

The external framework in this example is going to supply the language to the Sample Angular application. Assume that the initial value of the language is 'en' and now if we update it to 'es' I see that HttpRequestInterceptor is first picking en and then es. So all the API requests take 'Accept-Language' header value as en instead of es. If the external framework is sending language 'fr' then in this case I see the HttpRequestInterceptor is first picking es and then fr. Hence there will be few API requests taking 'Accept-Language' header value as es instead of fr.

Can anyone help me to know how to fix this issue?

2 Answers 2

2

try to replace setheaders with headers like this.

const request = req.clone({headers: req.headers.set('Accept-Language',this.config.Language)});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Farhat for your response. I tried the above but no change in the response. I still see the same error.
I see that even though the external framework sends a different language from the one that was set initially the code: console.log( Request header value : ${request.headers.get("Accept-Language")} ); picks the old language only.
0

I know this is an old question, but in case of anyone struggling with setting the 'Accept-Language' header to all request in an interceptor, use this:

request = request.clone({
  setHeaders: {
    'Accept-Language': this.config.Language + ';q=0.9,en-US,en;q=0.8'
  }
});

This works on Angular 11.2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.