Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 翻译Ts文件中的文本-角度Ngx翻译_Angular_Typescript_Ngx Translate - Fatal编程技术网

Angular 翻译Ts文件中的文本-角度Ngx翻译

Angular 翻译Ts文件中的文本-角度Ngx翻译,angular,typescript,ngx-translate,Angular,Typescript,Ngx Translate,我想翻译我的typescript文件中存在的文本,因此每次我想在使用应用程序时更改语言时,文本都应该更改(例如将语言从英语更改为法语)。我尝试了以下代码,但没有成功 this.translate.get('example').subscribe(res => { this.title = res.title } 我也尝试过这个方法,效果很好,但我不想每次我想在从一种语言转换到另一种语言时翻译typescript文件中的内容时,都在不同的组件中添加相同的代码 this.translate.

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

this.translate.get('example').subscribe(res => { this.title = res.title }
我也尝试过这个方法,效果很好,但我不想每次我想在从一种语言转换到另一种语言时翻译typescript文件中的内容时,都在不同的组件中添加相同的代码

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)
)
this.title$:Observable=this.translate.onLangChange.pipe(
switchMapTo(this.translate.get('example')),
映射((结果:字符串)=>result.title)
)
然后在html中使用异步管道,而不是在ts文件中订阅

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


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

您能详细说明一下吗?您的答案不是我想要的。我只想在typescript文件中翻译,所以我不需要管道