Ionic4--多語言使用

1、在 app.module.ts 導入 translate 組件

import { TranslateModule, TranslateLoader, TranslateService } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';


//翻譯加載程序需要知道在哪裏加載i18n文件
//在Ionic的靜態資產管道中
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}


@NgModule({
    providers:[
        TranslateService
    ],
    imports:[
        HttpClientModule,
        ///多語言
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient]
            }
        }),
    ]

})

2、在 app.component.ts 設置默認語言

import { TranslateService } from '@ngx-translate/core';
constructor(
    private translate: TranslateService,
)

/**
 * 設置默認語言
 */
initTranslate() {
    /**
     * getBrowserLang() 方法獲取大類,如‘zh’,中文簡體中文繁體統稱
     */
    //設置翻譯字符串的默認語言和當前語言
    this.translate.setDefaultLang('zh-CN');
    console.log(this.translate.getBrowserLang());
    //獲取系統語言
    if (this.translate.getBrowserCultureLang() == 'zh-TW') {
      this.translate.use('zh-TW');
    } else  if (this.translate.getBrowserLang() == 'en') {
      this.translate.use('en');
    } else {
      this.translate.use('zh-CN');
    }
}

3、在多語言文件定義多語言

//json文件內部
{
    "login": {
        "button": "登錄",
        "title": "登錄",
        "selectSchool": "請選擇學校",
        "inputUserName": "請輸入用戶名",
        "inputPsw": "請輸入密碼",
        "loading": "正在登錄...",
    }
}

4、使用多語言

import { TranslateService } from "@ngx-translate/core";

public translateText: any = {};//多語言

constructor(
    public translate: TranslateService){
    this.translateAction();
}

//設置多語言
translateAction() {
    this.translate.get('login').subscribe((value) => {
      this.translateText = value;
    });
}

//使用
<ion-title>{{this.translateText.title}}</ion-title>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章