angular的國際化方案,采用ngx-translate來實現(xiàn)。
安裝模塊:
npm install @ngx-translate/core --save
在根模塊中導入:
// other moduleimport {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]代表使用的語言文件名稱。然后我們可以在跟組件中添加配置對應的加載項:
// other moduleimport {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,因為一個系統(tǒng)的翻譯是統(tǒng)一的,在開始應用的時候就需要設置好默認語言。這里使用translate.setDefaultLang('en')來設置默認語言為英文。然后使用translate.user('en')手動選擇使用英文。在切換語言的時候,我們使用translate.user([lang])來設置啟用哪個語言。
最后來使用翻譯,有多種使用的方式。來看看。
使用方式
使用Service的方式
在運行的時候,會先發(fā)起個請求通過Http獲取翻譯文件,通過Observable的方式應用參數(shù)上去,然后獲得翻譯的內(nèi)容。
// app.compent.tsthis.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里定義參數(shù)param:
const param = { value: 'world',};使用指令
管道的方式雖然方便,但參數(shù)還是需要在先定義好,這樣子變量多的話也比較繁瑣。使用指令的方式可以在程序中直接傳參:
<span [translate]="'Introduce.Name'" [translateParams]="{name: 'Jarvis'}"></span>或者直接將元素的內(nèi)容作為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里面動態(tài)的獲取值和賦值,這時候沒法使用模板語法,使用subscribe的方式又不利于代碼的組織,這時候我們需要即時翻譯來搞定了。方法定義:
instant(key: string|Array<string>), insterpolateParams?: Object):string|Object
調(diào)用的時候傳入key和對應的參數(shù),即可返回當前key的翻譯:
this.translate.instant('HELLO', {value: 'Jarvis'});但是需要注意的是,這個方法是同步的,默認加載器是異步的。使用這個方法需要確保翻譯文件已經(jīng)加載完成了,如果不確定,就應該用get的方式。
參考:
https://www.npmjs.com/package/@ngx-translate/core
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答