简体   繁体   English

如何使用 i18n 以角度转换自定义管道?

[英]How to translate custom pipes in angular using i18n?

I am translating my Angular 7 app using i18n and I have custom pipes that produce text.我正在使用 i18n 翻译我的 Angular 7 应用程序,并且我有生成文本的自定义管道。 How can I translate the text produced by the pipes?如何翻译管道产生的文本?

I stick to the i18n guideline provided by the angular docs, I use this xliff merge strategy for development and I use this tutorial for my builds per locale.我坚持 angular 文档提供的i18n 指南,我使用此xliff 合并策略进行开发,并使用本教程进行我的每个语言环境的构建。

For example, I am trying to translate this time ago pipe in which numbers are converted to text.例如,我试图翻译这段时间之前的管道,其中数字被转换为文本。

At the moment I have no idea how to translate custom pipes.目前我不知道如何翻译自定义管道。 I only know how to translate html tags using the i18n attribute, which does not seem to be applicable to the custom pipes that I use.我只知道如何使用i18n属性翻译 html 标签,这似乎不适用于我使用的自定义管道。

This angular i18n paragraph suggests to set a some kind of global variable in the main app.module.ts , but the examples are a bit scarce and (a) I don't know how to set the locale depending on the build per language as I do following this tutorial , (b) I don't know how to get the global locale into my custom pipe and (c) is it possible translate the contents for the pipe in the messages.<locale>.xlf files instead of within the pipe?这个有角度的 i18n 段落建议在主app.module.ts设置某种全局变量,但示例有点稀缺,并且 (a) 我不知道如何根据每种语言的构建设置语言环境我确实遵循本教程,(b) 我不知道如何将全局语言环境放入我的自定义管道中,(c) 是否可以翻译messages.<locale>.xlf管道的内容messages.<locale>.xlf文件而不是内部管道?

Usually what you can do in this situation, is add the translateService as a dependency into your pipe, and just translate from code.通常在这种情况下您可以做的是将 translateService 作为依赖项添加到您的管道中,然后从代码中进行翻译。

So your constructor in the pipe would look like:所以你在管道中的构造函数看起来像:

constructor(private changeDetectorRef: ChangeDetectorRef, private ngZone: NgZone, private tr: TranslateService) {}

And in your transform function you can return the text value with this:在您的转换函数中,您可以使用以下命令返回文本值:

// [...]
} else if (days <= 545) {
  return this.tr.instant('time.one-year-ago');
} else { // (days > 545)
  return this.tr.instant('time.years-ago', { years });
}
// [...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM