Search code examples
angularngx-translate

How to configure Angular application for multi language support


I did my research on the internet and my code is working as expected but I'm getting a console error. Here is my code:

src/assets/i18n/en-us.json

{
    "home": {
        "helloWorld": "Hello Wrold! I'm back",
        "greet": "I'm fine. Thank you. How are you?"
}

app.module.ts

HttpClientModule,
TranslateModule.forRoot( {
  loader: {
    provide: TranslateLoader, useFactory: (http: HttpClient) => { return new TranslateHttpLoader(http, './assets/i18n/','.json')},
          deps: [HttpClient]
    }
  }
)

Logic

supportLanguages =['en-us', 'en-uk', 'en-in', 'en-aus'];

constructor(private translateService: TranslateService) { 
  this.translateService.addLangs(this.supportLanguages);
  this.translateService.setDefaultLang('en-us');

  const browserLang = this.translateService.getBrowserLang();
  this.translateService.use(browserLang);
}

Template

<span class="first">{{'home.helloWorld' | translate}}</span>
<span class="first">{{'home.greet' | translate}}</span>

Code is working but why this console error is there. This will fail my unit tests also I suppose.

GEThttp://localhost:4200/assets/i18n/en.json [HTTP/1.1 404 Not Found 2ms]

ERROR Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://localhost:4200/assets/i18n/en.json", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:4200/assets/i18n/en.json: 404 Not Found", error: "\n<html lang="en">\n\n<meta charset="utf-8">\nError\n\n\n

Cannot GET /assets/i18n/en.json
\n\n\n" }

My browser language is also en-us:

enter image description here

Please point out my mistake


Solution

  • just use this code in your app.component.ts..

    this.translateService.use(navigator.language);
    

    The problem is your was passing different language file to .use() method, which is not at present in asset folder. So you need to pass correct language code to .use() method.

    navigator.language detects current browser language and gives you code of that language. and now you are passing correct code like en-US and now your asset will match file name with en-US.json and your current en file not found error will remove.