angular5 基於ngx-translate實現多語言切換


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM