【问题标题】:Translate text in Ts file - Angular Ngx Translation翻译 Ts 文件中的文本 - Angular Ngx Translation
【发布时间】:2020-06-30 00:39:26
【问题描述】:

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

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

我也试过了,效果很好,但是当我从语言更改为另一种语言时,每次我想翻译打字稿文件中的内容时,我不想在不同的组件中添加相同的代码

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

【问题讨论】:

    标签: angular typescript ngx-translate


    【解决方案1】:

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

    【讨论】:

    • 你能详细说明一下吗?
    【解决方案2】:

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

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

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

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

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

    【讨论】:

    • 你的答案不是我想要的。我只想在打字稿文件中翻译,所以我不需要管道
    猜你喜欢
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 2018-07-02
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多