Search code examples
angularionic2ng2-translate

Ng2-translate - Fallback to default language when file doesn't exist


I have set up ng2-translate which translates my entire app and I have an en-GB.json file which contains all of my translations. The problem I have now is that if the user's device is set to another language (e.g. 'en-US'), I get 404 errors saying that the file en-US.json doesn't exist.

I have tried this solution https://github.com/ocombe/ng2-translate#how-to-handle-missing-translations but it seems that I would have to set up a default value for every single translation which isn't great.

Is there a way to automatically fall back to using the en-GB.json file if en-US.json (and other language files) doesn't exist?

Thanks for any help.

Edit:

Forgot to mention that I also set a default language like so:

Globalization.getPreferredLanguage().then(
    res => {
      language = res.value;
      self.translate.setDefaultLang('en-GB');
      self.translate.use(language);
    }
  );

Solution

  • You could keep a reference to all languages you support in an array and check if the language is inside the array. If it exists, you set the language, if not you set your default language.

    const langs = [
        'en-GB',
        'fr-FR',
        'de-DE'
    ];
    
    let isSupported = this.langs.find(supportedLanguage => supportedLanguage === language);
    
    if(isSupported) self.language.set(language);
    else self.language.set('en-GB')