0

I have files errors.ts and content.ts with English content same way errorsEs.ts and contentEs.ts with Spanish content.etc. I am doing JIT compiler angular localization to translate the language. I have imported errors.ts and content.ts throughout the app.

As of now, I am replacing the translated language(Spanish, Italian) content into the English content.ts and errors.ts to run it as a different language. Is there any other way to do it without replacement of files?

Latika Agarwal
  • 973
  • 1
  • 6
  • 11
TamilRoja
  • 165
  • 1
  • 1
  • 13

1 Answers1

0

Sure, create translation files with locales in the name (I'll create one for the sake of the example) :

error.en-US.ts

export const errors = {
  http: {
    e404: `Error: resource not found on the server`
  }
};

Next, create an error service. In the constructor, get the user locale, load the file, then use it :

constructor() {
  if (window.navigator.languages) { this.language = window.navigator.languages[0]; } 
  else { this.language = window.navigator.userLanguage || window.navigator.language; }

  this.errors = require(`errors.${this.language}`).errors;
}

EDIT

console.log(window.navigator.languages);
console.log(window.navigator.userLanguage);
console.log(window.navigator.language);
  • (I must state that I do it from memory, you will have to adapt this to your own code, but it's totally doable) –  May 14 '18 at 11:39
  • what is that language array hold of? – TamilRoja May 14 '18 at 13:38
  • The locales, users usually have several of them with a pound for each of them. For instance, mine is `["fr-FR", "fr", "en-US", "en"]` –  May 14 '18 at 13:40
  • Property 'languages' does not exist on type 'Navigator'. Property 'userLanguage' does not exist on type 'Navigator'. I am getting this errors? – TamilRoja May 14 '18 at 13:57
  • You didn't use my code. If you did, `if (window.navigator.languages)` would have prevented that. The condition isn't there to be pretty ... –  May 14 '18 at 13:57