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