angular多语言配置

angular的国际化方案,采用ngx-translate来实现。html

安装模块:shell

npm install @ngx-translate/core --save

在根模块中导入:npm

// other module
import {TranslateModule} from '@ngx-translate/core';
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        // other module
        TranslateModule.forRoot(),

    ],
    providers: [
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

咱们但愿能够在一个固定的文件里面配置对应的翻译文件,而后在每一个用到的组件里面使用它,随意咱们须要借助TranslateHttpLoader来加载翻译文件。首先安装TranslateHttpLoader:json

npm install @ngx-translate/http-loader --save

翻译文件能够放在/assets/i18n/[lang].json中,[lang]表明使用的语言文件名称。而后咱们能够在跟组件中添加配置对应的加载项:bootstrap

// other module
import {TranslateModule} from '@ngx-translate/core';
// 自定义加载方法
export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http, './assets/i18n/', '.json?');
}
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        // other module
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient],
            }
        }),
    ],
    providers: [
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

而后咱们在翻译文件中配置一个简单的示例:app

// /asserts/il8n/en.json
{
  "Hello": "hello, {{value}}",
  "Introduce": {
    "Name": "my name is {{name}}.",
    "Today": "today is {{date}}, and now time is {{time}}"
  }
}

应用的时候咱们可使用点语法,例如:Introduce.Nameless

好了,定义好以后再来看如何使用。咱们可使用服务或管道或指令的方式来达到显示语言的效果。在使用以前,咱们须要在应用中初始化TranslateService异步

import { Component } from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  constructor(
      public translate: TranslateService,
  ) {
      this.translate.setDefaultLang('en');
      this.translate.use('en');
  }
}

我倾向于在跟组件的construct里面初始化TranslateService,由于一个系统的翻译是统一的,在开始应用的时候就须要设置好默认语言。这里使用translate.setDefaultLang('en')来设置默认语言为英文。而后使用translate.user('en')手动选择使用英文。在切换语言的时候,咱们使用translate.user([lang])来设置启用哪一个语言。ide

最后来使用翻译,有多种使用的方式。来看看。this

使用方式

使用Service的方式

在运行的时候,会先发起个请求经过Http获取翻译文件,经过Observable的方式应用参数上去,而后得到翻译的内容。

// app.compent.ts
this.translate.get(
    'Introduce.Name',
    {name: 'Jarvis'}
).subscribe((res: string) => {
    console.log('res', res); // res my name is Jarvis.
});
this.translate.get(
    'Introduce.Today',
    {
        date: new Date().getDate(),
        time: new Date().getTime()
    },
).subscribe((res: string) => {
    console.log('res', res); // res today is 22, and now time is 1534937370461
});

使用pipe的方式

<div>{{'Hello' | translate: param</div>

在js里定义参数param:

const param = {
    value: 'world',
};

使用指令

管道的方式虽然方便,但参数仍是须要在先定义好,这样子变量多的话也比较繁琐。使用指令的方式能够在程序中直接传参:

<span [translate]="'Introduce.Name'" [translateParams]="{name: 'Jarvis'}"></span>

或者直接将元素的内容做为key:

<span translate [translateParams]="{date: '10.11', time: '20:33'}">Introduce.Today</span>

应用html标签

能够在翻译文件中中定义简单的行级html标签

{
  "Hello": "hello, {{value}}",
}

要渲染它们,在任何元素上只须要将innerHTML属性和管道一同使用便可。

<p [innerHTML]="'Introduce.Name'| translate: param"></p>

经常使用方法

instant() 即时翻译

有些状况下,咱们要在js里面动态的获取值和赋值,这时候无法使用模板语法,使用subscribe的方式又不利于代码的组织,这时候咱们须要即时翻译来搞定了。方法定义:

instant(key: string|Array<string>), insterpolateParams?: Object):string|Object

调用的时候传入key和对应的参数,便可返回当前key的翻译:

this.translate.instant('HELLO', {value: 'Jarvis'});

可是须要注意的是,这个方法是同步的,默认加载器是异步的。使用这个方法须要确保翻译文件已经加载完成了,若是不肯定,就应该用get的方式。
参考:

相关文章
相关标签/搜索