繁体   English   中英

翻译 Ts 文件中的文本 - Angular Ngx Translation

[英]Translate text in Ts file - Angular Ngx Translation

我想翻译我的打字稿文件中存在的文本,所以每次我想在使用应用程序时更改语言时,文本都应该更改(例如将语言从英语更改为法语)。 我尝试了以下代码但没有用

this.translate.get('example').subscribe(res => { this.title = res.title }

我也试过这个,它工作正常,但我不想在每次我想在从语言更改为另一种语言时翻译打字稿文件中的某些内容时在不同的组件中添加相同的代码

this.translate.onLangChange.subscribe(() => {
                this.translate.get('example').subscribe(res => { this.title = res.title }
        });

您应该将翻译服务放在 app.component 中并在那里进行所有翻译,这样您就无需在其他任何地方复制

尝试以这种方式构建您的标题值:

this.title$: Observable<string> = this.translate.onLangChange.pipe(
  switchMapTo(this.translate.get('example')),
  map((result: string) => result.title)
)

然后在 html 中使用异步管道,而不是在 ts 文件中订阅。

如果您需要以编程方式转换您的值。 您每次都需要听onLangChange 您可以尝试在专用服务中抽象此逻辑。

我的建议是尝试使用翻译管道而不是尝试以编程方式设置值。

暂无
暂无

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

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