I5N的angular 5动态更改语言环境

j0w*_*j0w 7 locale internationalization angular-i18n angular

我正在尝试动态更改语言环境以更改i18n语言。我有两个文件,一个具有英语值,另一个具有法国值。

我现在尝试的是这样的:

 ngOnInit() {
    const localeName = localStorage.getItem('locale') || 'fr';
    import(`@angular/common/locales/${localeName}.js`).then(locale => {
      registerLocaleData(locale.default);
    });
  }
Run Code Online (Sandbox Code Playgroud)

但是它给了我以下错误:

error TS1323: Dynamic import cannot be used when targeting ECMAScript 2015 modules.
Run Code Online (Sandbox Code Playgroud)

关于如何动态地从英语切换到法语的任何想法?:/

j0w*_*j0w 6

好吧,不确定这是否是一个好的解决方案,但这就是我所做的。它适用于我的目的,因此也许可以帮助其他人。

在main.ts中:

if (localStorage.getItem('locale') === null) {
localStorage.setItem('locale', 'en');
}

const locale = localStorage.getItem('locale');
declare const require;
const translations = require(`raw-loader!./locale/messages.${locale}.xlf`);

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    {provide: TRANSLATIONS, useValue: translations},
    {provide: TRANSLATIONS_FORMAT, useValue: 'xlf'}
  ]
});
Run Code Online (Sandbox Code Playgroud)

在html代码中:

<a  mat-menu-item href="" (click)="changeLang('fr')">
    <mat-icon>settings</mat-icon>
    <span>FR</span>
  </a>

  <a  mat-menu-item href="" (click)="changeLang('en')">
    <mat-icon>settings</mat-icon>
    <span>EN</span>
  </a>
Run Code Online (Sandbox Code Playgroud)

在component.ts中:

changeLang(lang: string) {

    if (lang === 'fr') {
      localStorage.setItem('locale', 'fr');
    }

    if (lang === 'en') {
      localStorage.setItem('locale', 'en');
    }
  }
Run Code Online (Sandbox Code Playgroud)

不要对我大喊,我只是一个有角^^的新手

  • 你好,刚刚花了几个小时来解决类似的问题并了解页面的标准 i18n 和“热”翻译之间的主要区别,我认为使用 https://github.com/ngx-translate/core 可以获得更好的结果 (2认同)