我的 ngx-translate 无法获取 Ionic 4 中的当前语言

My ngx-translator is not able to get the Current language in Ionic4

我正在使用 ngx-translator 包,但它无法在我的应用程序中设置默认语言。

这是我的app.module.ts:

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

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule,
    TranslateModule.forRoot({
      loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [HttpClient]
      }
    }),
    AppRoutingModule, HttpClientModule],
    providers: [
    StatusBar,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

这是我的app.component.ts:

import { TranslateService } from '@ngx-translate/core';
constructor(private translate: TranslateService) {
    this.initializeApp();
    this.translate.setDefaultLang('en');
    }

这是我的tab1.page.ts:

 import { TranslateService } from '@ngx-translate/core';
 language: string = this.translate.currentLang;
 constructor(private translate: TranslateService) { 
 console.log('Default language:', this.translate.currentLang);
 }

当我控制 console.log('Default language:', this.translate.currentLang); 时,它在控制台中显示未定义。

这是我的customcomponent.component.html:

  <ion-select (ionChange)='setLanguage()'>
  <ion-select-option value='en' selected='true'>English</ion-select-option>
  <ion-select-option value='ar'>Arabic</ion-select-option>
  </ion-select>

我只是想在选定的框中显示选定的语言,但我的当前语言不起作用。

当我打印当前的Lang时,它显示未定义。

非常感谢任何帮助。

我也遇到了同样的问题。只需更改 app.component.ts

来自

this.translate.setDefaultLang('en');

this.translate.use('en');

就我而言:

我创建了这样的服务(提供者)

public changeLanguage(langCode:string){
   this.translate.use(langCode);
}

只需在任何组件的函数中传递语言名称

this.serviceProvider.changeLanguage("en");