在Ts文件中翻译文本-Angular Ngx翻译

时间:2020-03-18 21:22:53

标签: angular typescript ngx-translate

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

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

我也尝试过这种方法,并且效果很好,但我不想每次在从语言转换为另一种语言时要在打字稿文件中翻译某些内容时,都在不同的组件中添加相同的代码

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

2 个答案:

答案 0 :(得分:0)

您应该将翻译服务放在您的app.component中,并在其中进行所有翻译,因此您无需在其他任何地方进行复制

答案 1 :(得分:0)

尝试以这种方式构造标题值:

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

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

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

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