angular的坑永远都是那么多,当然了,主要还是我太菜~
基于ngx-translate实现多语言切换这个功能,我又是折腾了很久,下面是我实现的过程:
1、安装ngx-translate
需要安装@ngx-translate/core和@ngx-translate/http-loader,我的问题主要出在这个,angular的版本不同,要安装对应组件的版本也不同。
可以到官网查看对应版本的说明:https://github.com/ngx-translate/core
我本地用的是angular5,使用最新的版本,会报错。。
针对angular5版本的组件安装命令是:
npm install @ngx-translate/core@9.1.1 --save
npm install @ngx-translate/http-loader@2.0.1 --save
如果你用的不是angular5,可以到下面对应的changelog页面,查找对应的版本号:
https://github.com/ngx-translate/core/releases
https://github.com/ngx-translate/http-loader/releases
2、修改app.module.ts,添加对ngx-translate的支持
引入:
import { HttpClientModule,HttpClient } from '@angular/common/http'; import {TranslateModule,TranslateLoader} from '@ngx-translate/core'; import {TranslateHttpLoader} from '@ngx-translate/http-loader';
export function HttpLoaderFactory(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient);
}
@NgModule中添加支持(红色内容是添加的内容):
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
3、修改app.component.ts,添加对ngx-translate的支持
引入ngx-translate:
import {TranslateService} from '@ngx-translate/core';
初始化(红色内容为添加内容):
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen,public translate: TranslateService) { platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); translate.addLangs(["zh", "en"]); translate.setDefaultLang('zh'); const browserLang = translate.getBrowserLang(); translate.use(browserLang.match(/zh|en/) ? browserLang : 'zh'); });
4、添加语言资源文件:
添加en.json和zh.json文件,这两个文件要建在:
项目根目录-》src-》assets-》i18n目录下,我的en.json文件内容如下:
{
"search": "search",
"submit": "Submit",
"home": {
"firstPage": "First",
"lastPage": "Last",
"previousPage": "Previous",
"nextPage": "Next"
}
}
zh.json文件内容如下:
{
"search": "搜索",
"submit": "提交",
"home": {
"firstPage": "首页",
"lastPage": "末页",
"previousPage": "上一页",
"nextPage": "下一页"
}
}
5、在html页面中可以引入资源
{{'search' | translate}}
{{'home.firstPage' | translate}}
search和home.firstPage是资源的名称
官方参考例子:https://stackblitz.com/github/ngx-translate/example