使用 ngx-translate 在 Ionic/Angular 应用程序中设置语言时遇到问题

Having trouble with setting language in Ionic/Angular app with ngx-translate

我有一个使用两种语言的 Angular/Ionic 应用程序:

en_US
es_MX

这是我当前的环境:

Ionic:

   Ionic CLI                     : 6.16.1 (/Users/me/.nvm/versions/node/v14.17.0/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.2.3
   @angular-devkit/build-angular : 0.901.11
   @angular-devkit/schematics    : 9.1.11
   @angular/cli                  : 9.1.15
   @ionic/angular-toolkit        : 2.2.0

Cordova:

   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : ios 5.1.1
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.2.1, (and 6 other plugins)

Utility:

   cordova-res                          : 0.15.3
   native-run (update available: 1.4.0) : 1.3.0

System:

   Android SDK Tools : 26.1.1 (/Users/me/Library/Android/sdk)
   ios-deploy        : 1.11.4
   ios-sim           : 8.0.2
   NodeJS            : v14.17.0 (/Users/me/.nvm/versions/node/v14.17.0/bin/node)
   npm               : 6.14.13
   OS                : macOS Catalina
   Xcode             : Xcode 12.4 Build version 12D4e

我创建了两个语言 .json 文件并将它们添加到我的 /assets/i18n 文件夹中用于翻译。

我设置 app.module.ts 文件 我将默认语言设置为 en_US,如下所示:

this.translate.setDefaultLang("en_US");

我有一个默认加载的启动画面,提示用户他们希望使用哪种语言查看应用程序:

setLang(lang:string) {
    console.log(lang);
    this.translate.use(lang);
    this.router.navigateByUrl('/app/tabs/home', { replaceUrl: true });
  }

这会在整个应用程序中正确设置语言,但是,根据我的喜好,我让他们可以选择将语言设置回不同的选择:

updateAppLanguage() {
    console.log(this.appLanguage);
    this.translate.use(this.appLanguage);
}

如果我在启动画面中将语言设置为 es_MX,那么当我在首选项中更新我的语言时,它会按预期工作。每次都会切换语言。

但是,如果我在启动画面中将语言设置为 en_US,那么当我在首选项中更新语言时,语言根本不会切换。它在整个应用程序中始终使用英语。

关于我应该去哪里尝试解决这个问题有什么想法吗?我没有在控制台或通过 linting 看到任何错误。

我找到问题了。

我注意到,在更改我的首选项中的语言时,es_MX 会 return 一个空结果。

似乎没有预加载语言。

为了修复,在我的 preferences.module.ts 中,我将其添加到模块导入中:

import { HttpLoaderFactory } from '../../../app.module';

TranslateModule.forChild({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),