1

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

10
  • Your translation file is en-us.json but actual requested file is en.json. either rename that or change the used language to en-us Commented May 15, 2021 at 8:48
  • @JelleBruisten, It should not invoke e.json. My browser language is alo en-us. See I've added one screenshot just now. Commented May 15, 2021 at 8:51
  • @tanzeel in your asset folder where is en.json file ? Commented May 15, 2021 at 8:59
  • @GaurangDhorda, the path is src/assets/i18n/en-us.json Commented May 15, 2021 at 9:00
  • @GaurangDhorda, i dont have en.json. i have en-us.json and i want this also. Commented May 15, 2021 at 9:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.