[英]ngx-translate - Translating keys without component in TypeScript file
我将 Angular 与 @ngx-translate 模块一起使用。 我有以下文件(只是声明了一些常量):
// some.module.ts
const const1 = [
{
url: 'google.com',
},
{
url: 'google.de',
},
{
url: 'google.at',
},
];
const someOtherConst = [
{
text: 'please.translate.me', // <== Should be translated
},
];
基本上我想翻译常量someOtherConstant
内的关键text
的值,但我不知道如何。
TranslationService
的新实例,因为它需要一些我不应该(甚至不能)自己提供的参数。这似乎是一个如此简单的任务,但我似乎无法弄清楚如何。
你不能按照你想要的方式去做。 拥有翻译服务的全部意义在于您还可以动态切换语言,因此您无法使用翻译填充常量值。 您需要在使用常量的地方应用翻译。 最后,您可能希望在某处显示值。
如果要在组件中显示值,可以将常量作为属性公开,然后在模板中进行转换。
一个简单的组件:
@Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent {
public get textToTranslate() {
return someOtherConst[0].text;
}
}
翻译它的组件模板:
<h3>{{ textToTranslate | translate }}</h3>
如果您需要在代码中进行翻译,您需要在服务或组件中进行TranslateService
,您可以在其中注入TranslateService
并根据需要使用任何方法来获取翻译。
这是一项提供三种可能的翻译方式的服务:
@Injectable()
export class ServiceWithTranslations {
constructor(public translateService: TranslateService) {
// get text with current language
this.translateService.get(someOtherConst[0].text).subscribe((translatedText => {
console.log(translatedText);
}));
// gets translation and emits new value if language changes
this.translateService.stream(someOtherConst[0].text).subscribe((translatedText => {
console.log(translatedText);
}));
// gets translation with current language you need to be sure translations are already loaded so it is not reccomended
const translatedText = this.translate.instant(someOtherConst[0].text);
console.log(translatedText);
}
}
与我认为您想要的最接近的选择是创建一个服务来准备翻译,然后将此服务注入您需要翻译的组件或服务中。
以下是此类服务的基本示例:
@Injectable()
export class TranslationsService {
public translatedConsts = [];
constructor(private translateService: TranslateService) {
for (const textEntry of someOtherConst) {
const translatedConst = {
text: ''
};
this.translateService.stream(textEntry.text).subscribe((translatedText) => {
translatedConst.text = translatedText
});
this.translatedConsts.push(translatedConst);
}
}
}
只需将您的翻译JSON 文件(例如 en.json)的键作为常量的值,并在您的组件中使用翻译管道来获取翻译。 下面给出的例子:
// Your separate const file
export const textContent = [
{ name: CONSTANT_VALUE.title1, data: CONSTANT_VALUE.description1},
{ name: CONSTANT_VALUE.title2, data: CONSTANT_VALUE.description2}
]
//In your JSON
{
"CONSTANT_VALUE" : {
"title1": "John",
"description1": "Eats apple",
"title2": "Sam",
"description2": "Eats ice-cream"
}
}
//In your component template
<div *ngFor="let content of textContent">
<h4>{{content.name | translate}}</h4>
<p>{{content.data | translate}}</p>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.