Angular i18国际化,以编程方式更改语言 [英] Angular i18 internationalization, language change programmatically

查看:83
本文介绍了Angular i18国际化,以编程方式更改语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过此链接,我试图在Angular 6应用中实现i18国际化,以便在html模板中以英语和意大利语翻译一些文本和日期时间.

from this link I tried to implement the i18 internationalization in my Angular 6 app in order to translate in english and italian some text and datetime in my html template.

https://next.angular.io/guide/i18n

我知道此功能分为三个阶段:

I understood that this function consist in 3 phases:

1)定义翻译文本.没问题,我创建了一个src/locale文件夹,其中包含2个文件messages.en.xlf(和message.it.xlf);这是en版本的示例.

1) Define translation text. No problem, I created a folder src/locale folder with 2 files messages.en.xlf (and message.it.xlf); here is an example for en version.

<trans-unit id="introductionHeader" datatype="html">
  <source>Hello i18n! (en-EN)</source>
  <note priority="1" from="description">An introduction header for this sample</note>
  <note priority="1" from="meaning">User welcome</note>
</trans-unit>

2)将此文本链接到带有适当标签的html页面,这里也没有问题,在我的app.translations.html中有我的示例标签.

2) link this text to html pages with appropriates tag, and also here no problem, there is my example tag in my app.translations.html.

<h1 i18n="User welcome|An introduction header for this sample">
    Hello i18n!
</h1>

现在,我阅读了启动过程中本地化应用程序的方式(第3阶段)(在Angular.json文件中进行一些编辑,然后使用配置选项启动ng服务);但是,相反,我将以编程方式更改应用程序的语言.换句话说,我想要一个诸如

Now, I read the way (3. phase) to localize the app during startup (some editing in Angular.json file and start ng serve with configuration option); but, instead of this, I would change the language of the app programmatically. In other words, I want a command such as

SwitchAppLanguage('en')

,例如,以便用户可以通过按钮自行更改它,或者应用程序可以读取浏览器的默认语言来进行更改.我该怎么办?

for example, so that the user can change it self by a button or the app can do this reading the browser default language. How can I do this?

非常感谢!

我试图以这种方式编辑我的angular.json文件

I tried to edit my angular.json file in this way

"configurations": {
  "production": {
     "i18nFile": "src/locale/messages.it.xlf",
     "i18nFormat": "xlf",
     "i18nLocale": "it",
(...)

而且,在ng构建并提供ng服务后,我希望看到意大利语文本,但这种情况不会发生(并且该应用程序可以正常启动并提供服务).我怎么了谢谢!

And, after ng build and ng serve, I expect to see the italian text but it doesn't happens (and the app start and serve correctly). What do I wrong? Thanks!

推荐答案

因此,如果您使用JIT,则可以使用webpacks loader来热交换语言文件:

So if you use JIT, you can use webpacks loader to hotswap language files:

main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { getTranslationProviders } from './app/providers/i18n.provider';
import { LocaleService } from './app/services/locale.service';

if ( environment.production ) {
  enableProdMode();
}

const locale = new LocaleService();
locale.getLocale().then( ( localeValue ) => {
  getTranslationProviders( localeValue ).then( providers => {
    platformBrowserDynamic().bootstrapModule( AppModule, { providers } )
      .catch( err => console.log( err ) );
  } );
} );

i18n.provider

import { TRANSLATIONS, TRANSLATIONS_FORMAT } from '@angular/core';
declare const require;

export function getTranslationProviders( locale: string ): Promise<any[]> {

  // Get the locale id as arugment or from the global
  //
  const localeValue = locale || document[ 'locale' ] as string;


  // return no providers if fail to get translation file for locale
  //
  const noProviders: Object[] = [];

  // No locale or AU, doesn't require translation
  //
  if ( !localeValue || localeValue === 'au' ) {
    return Promise.resolve( noProviders );
  }
  try {
    const translations = require( `raw-loader!../../locale/messages.${ localeValue }.xlf` );
    return Promise.resolve( [
      { provide: TRANSLATIONS, useValue: translations },
      { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
    ] );
  } catch ( error ) {
    console.error( error );
    return Promise.resolve( noProviders );
  }

}

local.service

import { WindowRef } from 'app/services/windowRef.service';
import { environment } from 'environments/environment';


@Injectable()

export class LocaleService {
  _locale: string;
  set locale( val: string ) {
    this._locale = val;
  }
  get locale() {
    return this._locale;
  }


  constructor() {
    this.setLocale();
  }

  setLocale() {
    const winRef = new WindowRef();

    this.locale = ( environment.countryLookup[ document.location.hostname ] || 'au' ).toLowerCase();

    const match = document.location.search.match( /au|nz/ );

    if ( match ) {
      this.locale = match.shift();
    }
    // store locale in document
    //
    winRef.nativeWindow.document.locale = this.locale;
  }

  getLocale(): Promise<string> {
    return Promise.resolve( this.locale );
  }

}

您将不得不对其进行一些重构以匹配您的项目,但是我希望您能掌握要点. 在Ivy支持正确的语言切换之前,这可能是一个解决方案.

You will have to refactor it a bit to match your project, but I hope you get the gist. This might be a solution until Ivy supports proper language switching.

这篇关于Angular i18国际化,以编程方式更改语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆