如何使用Transloco动态切换TypeScript组件语言无需重载?
解决TranslocoService动态更新TypeScript中生成文本的问题
方法一:利用Transloco的Observable自动同步(推荐)
直接调用translateObject只会拿到当前语言的静态值,不会监听语言变化。改用监听语言切换的Observable,让数组自动更新:
import { TranslocoService } from '@ngneat/transloco'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; // 把数组定义为可观察对象 diccionarioReports$: Observable<Array<{ titulo: string; /* 你的其他属性 */ }>>; constructor(private translocoService: TranslocoService) { // 订阅语言变化事件,每次切换都重新生成翻译后的数组 this.diccionarioReports$ = this.translocoService.langChanges$.pipe( map(() => [ { titulo: this.translocoService.translateObject('reports.report1.title'), // 其他属性... }, { titulo: this.translocoService.translateObject('reports.report2.title'), // 其他属性... } ]) ); }
在模板里用async管道订阅这个Observable,语言切换时会自动刷新内容:
<div *ngFor="let report of diccionarioReports$ | async"> {{ report.titulo }} </div>
方法二:手动监听语言切换事件更新数组
如果不想用Observable,也可以在语言切换时手动触发数组重新生成:
import { TranslocoService } from '@ngneat/transloco'; diccionarioReports: Array<{ titulo: string; /* 你的其他属性 */ }> = []; constructor(private translocoService: TranslocoService) { // 初始化生成数组 this.refreshReportsDictionary(); // 监听语言变化,每次切换都重新生成 this.translocoService.langChanges$.subscribe(() => { this.refreshReportsDictionary(); }); } private refreshReportsDictionary() { this.diccionarioReports = [ { titulo: this.translocoService.translateObject('reports.report1.title'), // 其他属性... }, { titulo: this.translocoService.translateObject('reports.report2.title'), // 其他属性... } ]; }
问题核心原因
HTML里的transloco管道内部自动订阅了langChanges$事件,所以能随语言切换自动更新。而直接调用translateObject只是一次性获取当前语言的翻译值,不会监听后续的语言变化,必须手动关联语言切换事件才能实现动态更新。
内容的提问来源于stack exchange,提问作者user19580074
相关产品推荐
相关产品推荐

