angular的国际化方案,采用ngx-translate
来实现。
安装模块:
1 | npm install @ngx-translate/core --save |
在根模块中导入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // other module import {TranslateModule} from '@ngx-translate/core'; @NgModule({ declarations: [ AppComponent, ], imports: [ // other module TranslateModule.forRoot(), ], providers: [ ], bootstrap: [AppComponent] }) export class AppModule { } |
我们希望可以在一个固定的文件里面配置对应的翻译文件,然后在每个用到的组件里面使用它,随意我们需要借助TranslateHttpLoader
来加载翻译文件。首先安装TranslateHttpLoader
:
npm install @ngx-translate/http-loader --save
翻译文件可以放在/assets/i18n/[lang].json
中,[lang]
代表使用的语言文件名称。然后我们可以在跟组件中添加配置对应的加载项:
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 { }
然后我们在翻译文件中配置一个简单的示例:
// /asserts/il8n/en.json { "Hello": "hello, {{value}}", "Introduce": { "Name": "my name is {{name}}.", "Today": "today is {{date}}, and now time is {{time}}" } }
应用的时候我们可以使用点语法,例如:Introduce.Name
。
好了,定义好之后再来看如何使用。我们可以使用服务或管道或指令的方式来达到显示语言的效果。在使用之前,我们需要在应用中初始化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])
来设置启用哪个语言。