ionic2 ng2-translate不适用于模态

时间:2016-12-21 10:11:31

标签: angular ionic-framework ionic2 ng2-translate

我在使用ng2-translate和ionic2中的模态时遇到了问题。正常页面中的翻译正在发挥作用。

这是我的 app.module.ts 文件:

import ...
@NgModule({
    declarations: [
    MyApp,
    //...
  ],
  imports: [
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useFactory: (createTranslateLoader),
      deps: [Http]
    }),
    IonicModule.forRoot(MyApp),
  ],
  exports: [
    TranslateModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    //...
  ],
  providers: [Storage, {provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}
export function createTranslateLoader(http: Http) {
  return new TranslateStaticLoader(http, 'assets/i18n', '.json');
}

例如,在我的信息中心中,我可以使用以下HTML代码并获得正确的翻译:

<h2>{{'general.tasks' | translate}}</h2>

但是当我现在通过以下代码从离子角开启ModalController的新模态时:

let taskModal = this.modalCtrl.create(TaskCancelPage, {'task': task});
taskModal.onDidDismiss(data => {
    console.log(data);
});
taskModal.present();

在新的TaskCancelPage中使用相同的HTML代码

<h2>{{'general.tasks' | translate}}</h2>

但在这里我只得到 general.tasks 而不是翻译后的价值。

1 个答案:

答案 0 :(得分:0)

这对我有用,这就是我所做的:

在[project] /src//app.module.ts中:

import { TranslateModule, TranslateStaticLoader, TranslateLoader } from 'ng2-translate/ng2-translate';
export function createTranslateLoader(http: Http) {
    return new TranslateStaticLoader(http, './assets/i18n', '.json');
}

import { TranslationService } from '../services/translation/translation';
//custom pipe
import { CapitalizePipe } from '../custom-pipes/capitalize/capitalize';    

@NgModule({
  declarations: [
     ...,
     CapitalizePipe,
     ....
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    TranslateModule.forRoot({provide: TranslateLoader,
      useFactory: (createTranslateLoader),
      deps: [Http]})
  ],
  bootstrap: [IonicApp],
  entryComponents: [
     ...
  ],
  providers: [
    TranslationService,
    .... 
  ]
})

在[project] /src/app/app.component.ts

        ...
        import { TranslationService } from '../services/translation/translation';
        import { CapitalizePipe } from '../custom-pipes/capitalize/capitalize';

        @Component({
          templateUrl: 'app.html',
        })
        export class MyApp {
          ....

          constructor(
            ...,
            public translationService: TranslationService, ...
          ) {}
          ....
        ngOnInit() {
            return this.defineLang().then(
             (event) => {
                 console.log(MyApp.CLASS_TAG + " this.defineLang() fired: ",event , " getLangs is " , this.translationService.getLangs());
               this.[yourFunctionToDefineRootPage]();
             }
           );
         }
    ...
      private defineLang(): Promise<any> {
        let appDfltLang = 'fr';
          this.translationService.getBestLanguageAccordingToBrowserAvailability(appDfltLang);
        let promise = this.translationService.langSettingOnInit();
        return promise;
      }
....
}
/src/custom-pipe/capitalize/capitalize.ts中的

import { PipeTransform, Pipe } from '@angular/core';
@Pipe({name:'capitalize'})

export class CapitalizePipe implements PipeTransform {
       transform(value?: any,args?: any): any{
                return (!!value)?value.charAt(0).toUpperCase()+value.substr(1):value;
       }

        }
/src/services/translation/translation.ts

中的

import { Injectable } from '@angular/core';
import { LangChangeEvent, TranslateService } from 'ng2-translate/ng2-translate';
import { Observable } from 'rxjs/Observable';
import { CapitalizePipe } from '../../custom-pipes/capitalize/capitalize';

@Injectable()
export class TranslationService {

    private static readonly CLASS_TAG = "TranslationService";

    private availableLang: Array<string> = ["fr","en","nl"];
    private defaultLanguage:string = "en";

    constructor(
        private translateService: TranslateService
    ) { }

    setDefaultLang(lang: string) {
        return this.translateService.setDefaultLang(lang);
    }


    use(lang: string): Observable<any> {
        let brLgSubStr:string = this.getBrowserLang().substr(0,2);
        let findLg:number = this.availableLang.indexOf(brLgSubStr);
        if(findLg==-1){
            lang = this.defaultLanguage;
        }

        return this.translateService.use(lang);
    }

    getCurrentLang(): string {
        return this.translateService.currentLang;
    }

    getDefaultLang(): string {
        return this.translateService.getDefaultLang();
    }

    getBestLanguageAccordingToBrowserAvailability(appDfltLang:string) {
    console.log(TranslationService.CLASS_TAG + "getBestLanguageAccordingToBrowserAvailability() starts ");

        let brLang = this.getBrowserLang().substr(0,2);
        let brLangAmongPossibilities:boolean = false;

        for(let i in this.availableLang){
            if(this.availableLang[i]==brLang){
                brLangAmongPossibilities=true;
            }
        }
        if(brLangAmongPossibilities){
            this.translateService.use(brLang);
        } else {
            this.translateService.use(appDfltLang);

        }

        this.translateService.setDefaultLang(appDfltLang);

    }

    getBrowserLang():string {
        return this.translateService.getBrowserLang();
    }

    getLangs():Array<string> {
        return this.translateService.getLangs();
    }

    getAvailableLangs():Array<string>{
        return this.availableLang;
    }

    langSettingOnInit(): Promise<LangChangeEvent> {
        return new Promise((resolve, reject) => {
            this.translateService.onLangChange.subscribe(
                (event) => {
                    resolve(event);
                },
                (error) => {
                    console.log(TranslationService.CLASS_TAG + "onLangChangeInit() error: " ,error);
                    reject(error);
                }
            );
        });
    }

    instant(key: string | Array<string>, interpolateParams?: Object): string | any {
        let result =  key && this.translateService.instant(key, interpolateParams);
        result = (result !== key) ? result : '';

        if (key && !result) {
            console.error(`[not translated key]::${key}`);
        }

        return result;
    }

     instantCapitalize(key: string | Array<string>, interpolateParams?: Object): string | any {

        return new CapitalizePipe().transform(this.instant(key));
    }
}

然后在您要使用它的页面(模态或非模态)中导入服务:

import { TranslationService } from '[root folder]/services/translation/translation';

并在页面的构造函数中声明服务:

@Component({
    selector:'custom',
    templateUrl: 'custom.html'

})
export class CustomPage {

    constructor(...,public translationService:TranslationService,...){
    }
    ....
}

在你的html模板中调用它:

<[some text tag]>{{ "[some id word from your trad file]" | translate | capitalize }}</some text tag]>

或者如果您不想将第一个字母大写:

<[some text tag]>{{ "[some id word from your trad file]" | translate  }}</some text tag]>

如果你打电话给AlertController,你可以在一个页面中执行 - :

this.translationService.instantCapitalize("[some id word from your trad file]");

或者如果您不想将第一个字母大写:

this.translationService.instant("[some id word from your trad file]");

因为某些原因,只能阅读[项目] / wwww / assets / i18n / [2字符语言代码]下的传统文件.json