1.安裝html
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader
2.配置(文本背景部分爲該模塊新增的)~app.module.ts
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { I18nComponent } from './i18n.component'
import { HttpClientModule ,HttpClient} from '@angular/common/http';
export function createTranslateHttpLoader(http: HttpClient) {
return new TranslateHttpLoader(http, '/app/assets/i18n/', '.json');
}
imports: [
BrowserModule,
FormsModule, // <-- import the FormsModule before binding with [(ngModel)]
ReactiveFormsModule,
AppRoutingModule,//路由模塊
CommonModule,
FileUploadModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateHttpLoader),
deps: [HttpClient]
}
})
],
3.組件部分(i18n.component.ts)npm
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core'
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'i18n.component.html'
})
export class I18nComponent implements OnInit {
constructor(private translateService: TranslateService) {
}
ngOnInit() {
this.translateService.addLangs(["ch", "en"]);
this.translateService.setDefaultLang("ch");
const browserLang = this.translateService.getBrowserLang();
this.translateService.use(browserLang.match(/ch|en/) ? browserLang : 'ch');
}
}
4.i18n.component.html
<div>
<span> hello dih</span>
<h1>{{ 'hello' | translate }}</h1>
</div>
5.建立須要翻譯的json語言 (注意:該路徑是app.module中的調用的路徑)json
en.json瀏覽器
{app
"hello": "the word is hello"
經過以上配置便可完成i18n國際化語言的轉化,可是還有些坑須要本身踩。。。。ide
如下是經過本身的實戰經驗解決的問題,也許能幫助你們,往下看this
1.bug1 (GET http://localhost:3000/@ngx-translate/core 404 (Not Found))spa
解決方案以下:翻譯
1. 須要在systemjs.config.js中添加component
'@ngx-translate/core': 'npm:@ngx-translate/core/bundles/core.umd.js',
'@ngx-translate/http-loader': 'npm:@ngx-translate/http-loader/bundles/http-loader.umd.js',
2.bu2(http 404 (Not Found))
解決方案以下:
1.在app.module.ts中把http換成HttpClient,上面的已經修改後的
2.須要在systemjs.config.js中添加@angular/common/http
3.bug3 (tslib 404 not found)
解決方案以下:
1.在systemjs.config.js中添加如下配置
path:新增'npm:': 'https://unpkg.com/'
map新增'tslib': 'npm:tslib@1.6.1'
經過以上配置,便可根據瀏覽器語言設置來加載國際化語言了
英文以下:
中文以下:
谷歌瀏覽器~高級~語言~移動頂部~保存~刷新F5~語言