您无法按照自己的方式进行操作。拥有翻译服务的全部要点是,您还可以动态切换语言,因此您不能使用翻译填充常量值。您需要在使用常量的地方应用转换。最后,您可能希望将这些值显示在某个位置。
如果要在组件中显示值,可以将常量作为属性公开,然后在模板中进行翻译。
一个简单的组件:
@Component({
selector: 'app-root',templateUrl: 'app.component.html'
})
export class AppComponent {
public get textToTranslate() {
return someOtherConst[0].text;
}
}
翻译它的组件模板:
<h3>{{ textToTranslate | translate }}</h3>
如果您需要代码翻译,则需要在服务或组件中进行翻译,您可以在其中注入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)作为常量的值,然后在组件中使用 translate 管道 即可获得翻译.下面给出的例子:
// 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>
本文链接:https://www.f2er.com/2931548.html