gpt4 book ai didi

@ngx-translate 和 ngx-translate-messageformat-compiler 的 Angular 复数化无法正确初始化

转载 作者:太空狗 更新时间:2023-10-29 18:01:15 69 4
gpt4 key购买 nike

我执行了以下步骤

(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 文件:

断言/i18n/en.json

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

断言/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 得到了预期的结果:

enter image description here

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

enter image description here

最佳答案

这方面有任何更新吗?我使用的解决方法是等到语言完成设置后再显示我的模板。例如,在我的 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>

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

关于@ngx-translate 和 ngx-translate-messageformat-compiler 的 Angular 复数化无法正确初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47476879/

69 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com