3

使用 ionic 3 应用程序的 ngx 翻译对我不起作用。下面是我的代码:

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);

    });
  }
}

在上面的文件中,我正在检查本地数据库中的存储首选项,然后在加载应用程序时将其设置为默认语言。

我的 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 {}

主页.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');
  }

}

主页.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>

侧边菜单页面 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);
  }

}

语言.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 {}

语言.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"
}

嗨.json

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

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

在更改语言时,它会显示keys翻译。请让我知道我做错了什么?

4

4 回答 4

6

我已经更新了我的语言模块,这对我有用,不确定这是否正确,但它有效。

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 {}

我添加了子加载器并在language.module.ts中导出 TranslateHttpLoader

语言.ts

langselect(form: NgForm){
    let langselcode = this.langform.value.langcode;
    this.storage.set('AppLangcode', langselcode);
    this.translate.use(langselcode);
  }
于 2017-06-22T12:04:52.920 回答
5

我花了几个小时让它在 Ionic 3 上运行。最后我不得不将 HttpClientModule 添加到 app.module.ts 的导入部分。希望有帮助。

[2]:使用 HttpClient 代替 Http

[3]:添加HttpClientModule

[4]:使用 HttpClient 代替 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/[你的页面]/[你的页面].module.ts

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

],

于 2017-09-29T14:45:57.370 回答
2

我有同样的问题并设法解决它。我懒惰地加载页面,当我尝试从组件更改语言时出现问题。他是我修好的。

app.component.ts

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

事件提供者.ts

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

将 event-provider.ts 导入 App Module 并包含在提供程序中。

现在您可以将它导入到任何需要更改语言并发出值的组件中。

自定义标头组件.ts

setLanguage(val:string) {
  this.eventProvider.setLang(val);
}
于 2018-03-13T08:47:43.517 回答
1

最后,我通过HttpClientModuleapp.module.ts. 也许它有帮助。

第一个:导入HttpClientModule 第二个:使用HttpClient而不是Http.

所以,代码如下: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');
}

app.component.ts中添加这一行constructor

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

然后你必须在路径中创建两个JSON文件。./assets/i18n/

en.JSON

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

然后在您的应用程序中使用PIPE这样的过滤器。

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

或者

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

我们也可以通过一个parameter.

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

或者

<h1 [translate]="'text'" [translateParams]="{value: 'ngx-translate'}"></h1>
于 2018-01-24T09:00:24.877 回答