[英]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.