简体   繁体   English

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

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

I want to translate text exist in my typescript file so each time I want to change the language while I am using the application the text should change (example change language from english to frensh).我想翻译我的打字稿文件中存在的文本,所以每次我想在使用应用程序时更改语言时,文本都应该更改(例如将语言从英语更改为法语)。 I tried the following code but didn't works我尝试了以下代码但没有用

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

Also I tried this and It worked fine but I don't want to add same code in different components every time I want to translate something in typescript file when I change from language to another我也试过这个,它工作正常,但我不想在每次我想在从语言更改为另一种语言时翻译打字稿文件中的某些内容时在不同的组件中添加相同的代码

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

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

Try constructing your title value this way :尝试以这种方式构建您的标题值:

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

Then use async pipe in your html instead of subscribing in your ts file.然后在 html 中使用异步管道,而不是在 ts 文件中订阅。

If you need to translate your value programmatically.如果您需要以编程方式转换您的值。 You need to listen to onLangChange each time.您每次都需要听onLangChange You could try to abstract this logic in a dedicated service.您可以尝试在专用服务中抽象此逻辑。

My advice is to try to use the translate pipe instead of trying to set the value programmatically.我的建议是尝试使用翻译管道而不是尝试以编程方式设置值。

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

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