我正在将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
},
];
基本上,我想在常数text
内转换键someOtherConstant
的值,但我不知道如何。
TranslationService
的新实例,因为它需要一些我不应该(甚至不能)自己提供的参数。这似乎是一个简单的任务,但我似乎无法弄清楚如何。
您无法按照自己的方式进行。拥有翻译服务的全部要点是,您还可以动态切换语言,因此您不能使用翻译填充常量值。您需要在使用常量的地方应用转换。最后,您可能希望将这些值显示在某个位置。
如果要在组件中显示值,可以将常量作为属性公开,然后在模板中转换。
一个简单的组件:
@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);
}
}
}