ngx-translation issue with ionic 3 app

2019-04-01 12:08发布

问题:

ngx translation with ionic 3 app not working for me. below is my code:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpModule,Http } from '@angular/http';
import { IonicStorageModule } from '@ionic/storage';

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

import { MyApp } from './app.component';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';



export function createTranslateLoader(http: Http) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicStorageModule.forRoot(),
    TranslateModule.forRoot({
                    loader: {
                      provide: TranslateLoader,
                      useFactory: (createTranslateLoader),
                      deps: [Http]
                    }
                  }),
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
  ]
})
export class AppModule {}

app.component.ts

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Storage } from '@ionic/storage';
import { TranslateService } from '@ngx-translate/core';


@Component({
  templateUrl: 'app.html'
})

export class MyApp {
  @ViewChild(Nav) nav: Nav;
  public rootPage: any;

  constructor(public platform: Platform, 
    public statusBar: StatusBar, 
    public splashScreen: SplashScreen,
    public storage: Storage,
    public translate: TranslateService) {

    this.storage.get('AppLangcode')
          .then((AppLangcode) => {
            if(AppLangcode==null){
              translate.setDefaultLang('en');
            }else{
              translate.setDefaultLang(AppLangcode);
            }
          })
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.menu.swipeEnable(false);

    });
  }
}

In above file i am checking storage preference in local db and then set it to default language on load application.

My RootPage home.module.ts

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';
import { TranslateModule } from '@ngx-translate/core';

@NgModule({
  declarations: [
    HomePage,
  ],
  imports: [
    IonicPageModule.forChild(HomePage),
    TranslateModule.forChild()
  ],
  exports: [
    HomePage
  ]
})
export class HomePageModule {}

home.ts

import { Component} from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { TranslateService } from '@ngx-translate/core';

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, 
    public navParams: NavParams,
    public storage: Storage,
    public translate: TranslateService,) {

  }

  ionViewDidLoad() {
    //console.log('ionViewDidLoad HomePagePage');
  }

}

home.html

<ion-header>
  <ion-navbar color='navbarColor'>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title><img src="assets/icon/logo.png" alt="Ionic logo"></ion-title>
  </ion-navbar>
</ion-header>

<ion-content  class="grid-basic-page">
    <ion-grid>
        <ion-row>
          <ion-col (click)="openPage('QuickBookPage');">
            <div><img src="assets/icon/icon-book-cylinder.png">{{"quick_book_pay" | translate}}</div>
          </ion-col>
          <ion-col (click)="openPage('RefilHistoryPage');">
            <div><img src="assets/icon/icon-quickpay.png">{{"refil_history" | translate}}</div>
          </ion-col>
        </ion-row>

        <ion-row>
          <ion-col (click)="openPage('ServicesPage');">
            <div><img src="assets/icon/icon-mechanic.png">{{"service_request" | translate}}</div>
          </ion-col>
          <ion-col>
          <button [disabled]="!clickhandle" (click)="emergencyCall();"><img src="assets/icon/icon-emergency.png">{{"emergency_helpline" | translate}}</button>
          </ion-col>
        </ion-row>  
  </ion-grid>

</ion-content>

Side Menu Page language.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,Events } from 'ionic-angular';
import { NgForm,FormBuilder, FormGroup, Validators  } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core';
import { Storage } from '@ionic/storage';


@IonicPage()
@Component({
  selector: 'page-language',
  templateUrl: 'language.html',
})
export class LanguagePage {
  public langform:FormGroup;
  public langcod:string;

  constructor(public navCtrl: NavController, 
    public navParams: NavParams,
    public formBuilder: FormBuilder,
    public translate: TranslateService,
    public storage: Storage) {

    this.storage.get('AppLangcode')
          .then((AppLangcode) => {

            if(AppLangcode==null){
              this.langcod = 'en';
              this.langform.get('langcode').setValue(this.langcod);
            }else{
              this.langcod = AppLangcode;
              this.langform.get('langcode').setValue(this.langcod);
            }
          })

    this.langform = formBuilder.group({
      langcode: [this.langcod, Validators.required]
    });
  }

  langselect(form: NgForm){
    let langselcode = this.langform.value.langcode;
    this.storage.set('AppLangcode', langselcode);
    this.translate.setDefaultLang(langselcode);
    this.translate.use(langselcode);
  }

}

language.module.ts

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { LanguagePage } from './language';
import { TranslateModule } from '@ngx-translate/core';

@NgModule({
  declarations: [
    LanguagePage,
  ],
  imports: [
    IonicPageModule.forChild(LanguagePage),
    TranslateModule.forChild()
  ],
  exports: [
    LanguagePage
  ]
})
export class LanguagePageModule {}

language.html

<ion-header>
 <ion-navbar color='navbarColor'>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title><img src="assets/icon/logo.png" alt="Ionic logo"></ion-title>
  </ion-navbar>
</ion-header>


<ion-content padding>
<form [formGroup]="langform" (submit)="langselect($event)">

    <ion-list radio-group  formControlName="langcode">
      <ion-row responsive-sm>
      <ion-col col-6>
            <ion-item>
              <ion-label>{{"english" | translate}}</ion-label>
              <ion-radio value="en" checked></ion-radio>
            </ion-item>
            <ion-item>
              <ion-label>{{"hindi" | translate}}</ion-label>
              <ion-radio value="hi"></ion-radio>
            </ion-item>
      </ion-col>
    </ion-row>

  </ion-list>

    <ion-row responsive-sm>
      <ion-col>
        <button ion-button block type="submit" [disabled]="!langform.valid">
            Submit
        </button>
      </ion-col>
    </ion-row>
  </form>

</ion-content>

en.json

{
    "english"   : "English",
    "hindi"     : "हिंदी",

    "quick_book_pay":"Quick Book & Pay",
    "refil_history":"Refill History",
    "service_request":"Service Request",
    "emergency_helpline":"Emergency Helpline"
}

hi.json

{
    "english"   : "English",
    "hindi"     : "हिंदी",

    "quick_book_pay":"त्वरित बुक और भुगतान करें",
    "refil_history":"रीफिल इतिहास",
    "service_request":"सेवा अनुरोध",
    "emergency_helpline":"आपातकालीन हेल्पलाइन"
}

On change language it show keys instead translation. Please let me know what wrong i am doing ?

回答1:

i have updated my language module and this worked for me, not sure if this is right way but it's worked.

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { LanguagePage } from './language';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpModule,Http } from '@angular/http';

export function createTranslateLoader(http: Http) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
  declarations: [
    LanguagePage,
  ],
  imports: [
    IonicPageModule.forChild(LanguagePage),
    TranslateModule.forChild({
            loader: {
                      provide: TranslateLoader,
                      useFactory: (createTranslateLoader),
                      deps: [Http]
                    }

        })
  ],
  exports: [
    LanguagePage
  ]
})
export class LanguagePageModule {}

i have added loader for child and export TranslateHttpLoader in language.module.ts

language.ts

langselect(form: NgForm){
    let langselcode = this.langform.value.langcode;
    this.storage.set('AppLangcode', langselcode);
    this.translate.use(langselcode);
  }


回答2:

I spent hours to get it working on Ionic 3. Finally I had to add HttpClientModule to the import section of app.module.ts. Hope that helps.

[2]: Use HttpClient instead of Http

[3]: Add HttpClientModule

[4]: Use HttpClient instead of Http

src/app/app.module.ts:

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

export function createTranslateLoader(http: HttpClient [2]) {
    return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
    ...
    imports: [
        BrowserModule,
        HttpModule,
        HttpClientModule [2],
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: createTranslateLoader,
                deps: [HttpClient] [3]
            }
        ...
    ...
}),

src/pages/[your-page]/[your-page].module.ts

imports: [
    IonicPageModule.forChild(LoginPage),
    TranslateModule.forChild(),

],



回答3:

I had the same issue and managed to fix it. I'm lazy loading the pages and the problem occurred when I try to change the language from a component. He's how I fixed it.

app.component.ts

this.translateService.addLangs(['en', 'lk']);
this.translateService.setDefaultLang("en");
this.eventProvider.currentLang.subscribe(lang => {
  this.translateService.use(lang);
});

event-provider.ts

import { EventEmitter } from '@angular/core';
export class EventProvider {
  public currentLang: EventEmitter<string> = new EventEmitter();
  setLang(val) {
    this.currentLang.emit(val);
  }
}

Import event-provider.ts to App Module and include in providers.

Now you can import it to any component where you need to change the language and emmit the value.

custom-header-component.ts

setLanguage(val:string) {
  this.eventProvider.setLang(val);
}


回答4:

Finally, i a solve this issue by using HttpClientModule in the import section of app.module.ts. maybe it helps.

First: Import HttpClientModule Second: Use HttpClient instead of Http.

So, the code is as follow: app.module.ts

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';

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

@NgModule({
    declarations: [
        HomePage,
    ],
  imports: [
    IonicPageModule.forChild(HomePage),
    HttpClientModule
    TranslateModule.forRoot({
        loader: {
            provide: TranslateLoader,
            useFactory: (createTranslateLoader),
            deps: [HttpClient ]
        }
    })
  ],
  exports: [
     HomePage
  ]
})

export class HomePageModule {}

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

In app.component.ts add this line in constructor.

import {TranslateService} from '@ngx-translate/core';
...
translate.setDefaultLang('en');//So English language set 

And then you have to create two JSON files in ./assets/i18n/ path.

en.JSON

{
   "title": "Translation demo",
   "text": "This is a simple demonstration app for {{value}}"
}

Then use in your app with PIPE filter like this.

<h1>{{'title' | translate}}</h1>

OR

<h1 [translate]="'title'"></h1>

We can also pass a parameter.

<h1>{{'text' | translate:{'value':'ngx-translate'} }}</h1>

OR

<h1 [translate]="'text'" [translateParams]="{value: 'ngx-translate'}"></h1>