【问题标题】:Angular pluralization with @ngx-translate and ngx-translate-messageformat-compiler doesn’t initialize properly@ngx-translate 和 ngx-translate-messageformat-compiler 的角复数未正确初始化
【发布时间】:2017-11-24 16:14:44
【问题描述】:

我执行了以下步骤

(1)新建了一个angular-cli项目(angular-cli 1.5.0)

(2) 添加依赖:

npm i @ngx-translate/core @ngx-translate/http-loader messageformat ngx-translate-messageformat-compiler --save

(3) 添加带有翻译的 JSON 文件:

asserts/i18n/en.json

{
    "translation": "translation",
    "things": "{count, plural, =0{Nothing} one{One thing} other{Lots of things}}"
} 

asserts/i18n/de.json)

{
    "translation": "Übersetzung",
    "things": "{count, plural, =0{Nichts} one{Ein Ding} other{Viele Dinge}}"
}

(4) 应用模块

import { AppComponent } from './app.component';

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      },
      compiler: {
        provide: TranslateCompiler,
        useClass: TranslateMessageFormatCompiler
      }
    }),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

(5) 应用组件

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  template: `
    <h1 translate>translation</h1>
    <p>{{'things' | translate:"{ count: 2 }"}}</p>
    <button (click)="selectLang('de')">De</button>
    <button (click)="selectLang('en')">En</button>
  `
})
export class AppComponent {

  constructor(private translate: TranslateService) {
    translate.setDefaultLang('de');
    this.translate.use('de');
    translate.addLangs(['en']);
  }

  selectLang(lang: string)  {
    this.translate.use(lang);
  }

}

页面加载没有问题并正确显示简单的翻译(“Überschrift”),但复数形式不起作用。

很好奇,通过单击“En”按钮将语言更改为 en 有预期的结果:

现在,切换回“De”也会以德语显示所需的结果。

【问题讨论】:

    标签: angular internationalization


    【解决方案1】:

    这方面有什么更新吗? 我使用的解决方法是等到语言完成设置后再显示我的模板。例如,在我的 appComponent 中,我将设置:

      langReady= false;
    
      constructor(private translate: TranslateService) {
        translate.setDefaultLang('de')
        translate.addLangs(['en']);
        this.translate.use('de').subscribe(()=>{
          this.langReady= true;
        });
      }
    

    在我的模板中,我将设置一个 *ngIf 来等待语言准备好显示,如下所示:

    <p *ngIf="timeElapsed">{{'things' | translate:"{ count: 1 }"}}</p>
    

    这不是一个非常优雅的解决方案,但它确实有效。您是否找到了设置消息编译器的更好方法?

    【讨论】:

    • @herbstein:除了您提到的解决方法之外,您找到解决方案了吗?
    • 除了您提到的解决方法之外,您是否找到了解决方案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2018-04-01
    • 2018-01-25
    • 2019-02-09
    • 1970-01-01
    • 2019-06-20
    相关资源
    最近更新 更多