angular-translate - Fallback language for determin

2019-06-15 00:08发布

问题:

I use angular-translate in my app. How can I register a fallback language if the determinePreferredLanguage() returns a language key my code doesn't know?

I want to fall back to english if someone from e.g. Sweden visits my site (language key: sv). But since I haven't listed sv in my registerAvailableLanguageKeys function, it fails, and the language-keys are shown to the user instead of the translation.

$translateProvider
    .registerAvailableLanguageKeys(['da-dk','en-us'], {
        'en_US': 'en-us',
        'en_UK': 'en-us',
        'da': 'da-dk',
    })
    .determinePreferredLanguage();

回答1:

Using wildcards is the best solution, you can just set en_* as follows:

    $translateProvider.useStaticFilesLoader({
       prefix: 'locales/locale-',
       suffix: '.json'
    })   

    .registerAvailableLanguageKeys(['en','fr','pt'], {
       'en_*': 'en',
       'fr_*': 'fr',
       'pt_*': 'pt',
       '*': 'en'
    })

    .determinePreferredLanguage()

    .fallbackLanguage('en');

for files:

locales/locale-en.json
locales/locale-fr.json
locales/locale-pt.json


回答2:

Hey I had a similar issue to yours, the way I solved it was :

I added this to my app.config

  $translateProvider.useStaticFilesLoader({
      prefix: 'the/directory/locale-',
      suffix: '.json'
    })

  .registerAvailableLanguageKeys(['en'])

  .determinePreferredLanguage()

  .fallbackLanguage('en');

and this to my app.run:

$rootScope.changeLanguage = function() {
  if(/[a-z]{2}_[A-Z]{2}/.test($translate.use())) {
    $translate.fallbackLanguage($translate.use().split('_')[0]);
  }
}

that way if the browser detects a language such as fr_BE it will try to fall back to fr and then once again en, in your case you would want sv. Also having the registerAvailableLanguageKeys seems to stop the determinePreferredLanguage() causing an error with the non-existant file issue. I hope this helps someone.



回答3:

You can use $translateProvider.fallbackLanguage(['en-us']) to determine your fallback language, and $translateProvider.preferredLanguage(langKey)to set your preferred language.

Also note that fallbackLanguage() can have an array of languages as a parameter, which means you can have several ordered fallback languages.