先用cli創(chuàng)建一個(gè)angular工程惫企。然后:
1.安裝 ngx-translate 模塊
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
2.在 Angular 項(xiàng)目配置
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, Http } from '@angular/http';
import { TranslateLoader, TranslateModule} from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { AppComponent } from './app.component';
export function createTranslateHttpLoader(http: Http) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');//也可以如此寫:return new TranslateHttpLoader(http);,這樣寫就是默認(rèn)在assets目錄下有i18n目錄暴区,并且語(yǔ)言文件是以.json結(jié)尾的。
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateHttpLoader),
deps: [Http]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:
import { Component } from '@angular/core';
import { TranslateService } from "@ngx-translate/core";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(public translateService: TranslateService) {}
ngOnInit() {
// --- set i18n begin ---
this.translateService.addLangs(["zh", "en"]);
this.translateService.setDefaultLang("zh");
const browserLang = this.translateService.getBrowserLang();//得到瀏覽器的默認(rèn)語(yǔ)言
this.translateService.use(browserLang.match(/zh|en/) ? browserLang : 'zh');//優(yōu)先使用瀏覽器語(yǔ)言
// --- set i18n end ---
}
}
3.添加多語(yǔ)言文件
在 src/app/assets/ 下創(chuàng)建 i18n 文件夾雇庙,并在文件夾內(nèi)創(chuàng)建 en.json 和 zh.json 文件
4.app.component.html
<div>
<span> test the i18n module: ngx-translate</span>
<h1>{{ 'hello' | translate }}</h1>
</div>
5.在 en.json 和 zh.json 文件中添加配置
en.json
{
"hello": "the word is hello"
}
zh.json
{
"hello": "你好"
}
6.在TS文件中使用:
constructor(
private translate: TranslateService) {}//注入
this.translate.instant('hello');//得到字符串
也可以這樣:
await this.translate.get('hello').toPromise();//得到字符串