本文只針對ngx-translate/core 6.x版本,若是你使用的是5.x或者更低的版本,請參照如下連接。git
https://github.com/ngx-translate/core/blob/fb02ca5920aae405048ebab50e09db67d5bf12a2/README.mdgithub
安裝npm
首先須要安裝npm依賴:json
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save // 針對Angular>=4.3
npm install @ngx-translate/http-loader@0.1.0 --save // 針對Angular<4.3
這裏須要注意,若是你使用的Angular版本是 Angular <4.3,那麼須要安裝http-loader@0.1.0版本。bootstrap
由於0.1.0之後的版本TranslateHttpLoader構造函數的第一個參數改成HttpClient類型,而非Http類型。promise
用法app
一、引入TranslateModule模塊
ionic
首先須要在你項目的root NgModule中引入TranslateModule.forRoot()模塊。通常在項目中默認命名爲app.module.ts。ide
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser'; import {HttpClientModule, HttpClient} from '@angular/common/http'; import {TranslateModule, TranslateLoader} from '@ngx-translate/core'; import {TranslateHttpLoader} from '@ngx-translate/http-loader'; import {AppComponent} from './app';
export function createTranslateLoader(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/', '.json'); } @NgModule({ imports: [ BrowserModule, HttpClientModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (createTranslateLoader), deps: [HttpClient] } }) ], bootstrap: [AppComponent] }) export class AppModule { }
這裏使用了TranslateHttpLoader
來加載咱們定義好的語言文件。"/assets/i18n/[lang].json"這裏的lang就是當前正在使用的語言。函數
注意:若是當前採用的是AOT編譯方式或者是ionic2工程,那麼useFactory對應的必須是一個export的自定義方法而非內聯方法。
即如下這種方式是不被容許的:
@NgModule({ imports: [ BrowserModule, HttpModule, TranslateModule.forRoot({ provide: TranslateLoader, useFactory: (http: HttpClient) => new TranslateStaticLoader(http, '/assets/i18n', '.json'), deps: [HttpClient] }) ], bootstrap: [AppComponent] }) export class AppModule { }
二、注入TranslateService
服務
在須要用到的component裏面注入TranslateService。
import {TranslateService} from '@ngx-translate/core';
而後在構造函數中定義當前應用的默認語言。
constructor(private translate: TranslateService) { // this language will be used as a fallback when a translation isn't found in the current language translate.setDefaultLang('en'); // use the brower's default lang, if the lang isn't available, it will use the 'en' let broswerLang = translate.getBrowserLang(); translate.use(broswerLang.match(/en|cn/) ? broswerLang : 'en'); }
三、翻譯文本書寫規則
有兩種方式能夠加載咱們翻譯好的語言文本。
首先你能夠把翻譯好的語言文本放到一個json文件中,而後經過TranslateHttpLoader來引用這個json文件。
例如:en.json
{ "HELLO": "hello {{value}}" }
另外也能夠經過setTranslation方法手動加載。
translate.setTranslation('en', { HELLO: 'hello {{value}}' });
同時,這裏的json結構是支持嵌套的。
{ "HOME": { "HELLO": "hello {{value}}" } }
以上結構,能夠經過"HOME.HELLO"來引用HELLO的內容。
四、使用方法
咱們能夠經過TranslateService
, TranslatePipe
或者 TranslateDirective這三種方式來獲取咱們翻譯的文本內容。
TranslateService:
translate.get('HELLO', {value: 'world'}).subscribe((res: string) => { console.log(res); //=> 'hello world' });
其中第二個參數{value: 'world'}是可選的。
TranslateService:
<div>{{ 'HELLO' | translate:param }}</div>
param能夠像以下方式在component裏面定義。一樣,這個參數也是可選的。
param = {value: 'world'};
TranslateDirective:
<div [translate]="'HELLO'" [translateParams]="{value: 'world'}"></div>
或者
<div translate [translateParams]="{value: 'world'}">HELLO</div>
五、使用HTML標籤
容許在你的翻譯文本中直接嵌入HTML標籤。
{ "HELLO": "Welcome to my Angular application!<br><strong>This is an amazing app which uses the latest technologies!</strong>" }
這時可使用innerHTML
來進行渲染。
<div [innerHTML]="'HELLO' | translate"></div>
公有屬性(public properties):
/** * The default lang to fallback when translations are missing on the current lang */ defaultLang: string; /** * The lang currently used * @type {string} */ currentLang: string; /** * an array of langs * @type {Array} */ langs: string[]; /** * a list of translations per lang * @type {{}} */ translations: any;
公有方法(public methods):
/** * Sets the default language to use as a fallback * @param lang */ setDefaultLang(lang: string): void; /** * Gets the default language used * @returns string */ getDefaultLang(): string; /** * Changes the lang currently used * @param lang * @returns {Observable<*>} */ use(lang: string): Observable<any>; /** * Gets an object of translations for a given language with the current loader * and passes it through the compiler * @param lang * @returns {Observable<*>} */ getTranslation(lang: string): Observable<any>; /** * Manually sets an object of translations for a given language * after passing it through the compiler * @param lang * @param translations * @param shouldMerge */ setTranslation(lang: string, translations: Object, shouldMerge?: boolean): void; /** * Returns an array of currently available langs * @returns {any} */ getLangs(): Array<string>; /** * @param langs * Add available langs */ addLangs(langs: Array<string>): void; /** * Returns the parsed result of the translations * @param translations * @param key * @param interpolateParams * @returns {any} */ getParsedResult(translations: any, key: any, interpolateParams?: Object): any; /** * Gets the translated value of a key (or an array of keys) * @param key * @param interpolateParams * @returns {any} the translated key, or an object of translated keys */ get(key: string | Array<string>, interpolateParams?: Object): Observable<string | any>; /** * Returns a stream of translated values of a key (or an array of keys) which updates * whenever the language changes. * @param key * @param interpolateParams * @returns {any} A stream of the translated key, or an object of translated keys */ stream(key: string | Array<string>, interpolateParams?: Object): Observable<string | any>; /** * Returns a translation instantly from the internal state of loaded translation. * All rules regarding the current language, the preferred language of even fallback languages will be used except any promise handling. * @param key * @param interpolateParams * @returns {string} */ instant(key: string | Array<string>, interpolateParams?: Object): string | any; /** * Sets the translated value of a key, after compiling it * @param key * @param value * @param lang */ set(key: string, value: string, lang?: string): void; /** * Allows to reload the lang file from the file * @param lang * @returns {Observable<any>} */ reloadLang(lang: string): Observable<any>; /** * Deletes inner translation * @param lang */ resetLang(lang: string): void; /** * Returns the language code name from the browser, e.g. "de" * * @returns string */ getBrowserLang(): string; /** * Returns the culture language code name from the browser, e.g. "de-DE" * * @returns string */ getBrowserCultureLang(): string;