1. 程式人生 > 實用技巧 >Angular2及以上版本的多語言問題

Angular2及以上版本的多語言問題

1、多語言的配置,正常安裝@ngx-translate/core和@ngx-translate/http-loader,注意@ngx-translate/core和@ngx-translate/http-loader的版本和當前使用的Angular版本有關,可以參考下圖:

也可參考官方文件:https://github.com/ngx-translate/core#5-use-the-service-the-pipe-or-the-directive

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

  

// 實現AOT編譯
export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

  

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
   // 此處省略其他無關模組配置
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      }
    }),
  ]

  

2、使用this.translateService.instant失效的問題

  失效原因:是因為在元件初始化的時候,翻譯檔案有可能沒有載入完成,這個方法要在確保翻譯檔案載入完成的情況下才能使用

  解決方案:1、可以使用get方法替代

       2、可以在系統啟動的時候通過在providers中做處理,具體程式碼如下

import { Injector, APP_INITIALIZER } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { LOCATION_INITIALIZED } from '@angular/common';

  

export function appInitializerFactory(translate: TranslateService, injector: Injector) {
  return () => new Promise<any>((resolve: any) => {
    const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
    locationInitialized.then(() => {
      const langToSet = 'zh_CN'
      translate.setDefaultLang('zh_CN');
      let lang = window.localStorage.getItem('lang') || 'zh_CN'
      if (lang && lang.indexOf('-')) {
        lang = lang.replace('-', '_')
      }
      translate.use(lang).subscribe(() => {
        // console.info(`Successfully initialized '${langToSet}' language.'`);
      }, err => {
        console.error(`Problem with '${langToSet}' language initialization.'`);
      }, () => {
        resolve(null);
      });
    });
  });
}

  

providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: appInitializerFactory,
      deps: [TranslateService, Injector],
      multi: true
    }
  ]

  關於instant失效的問題,參考來源:https://github.com/ngx-translate/core/issues/517