ngx-translate:如何动态翻译字符串数组

ngx-translate: How to translate dynamically array of strings

我想用 ngx-translate 创建星期几列表,但它不适用于异步管道。我遇到错误“错误 TS2769:没有超载匹配此调用。”我必须使用 JSON 文件。

TS:

    MON:Observable<string> = this.translate.get('CALENDAR.MON');
      TUE:Observable<string> = this.translate.get('CALENDAR.TUE');
      WED:Observable<string> = this.translate.get('CALENDAR.WED');
      THU:Observable<string> = this.translate.get('CALENDAR.THU');
      FRI:Observable<string> = this.translate.get('CALENDAR.FRI');
      SAT:Observable<string> = this.translate.get('CALENDAR.SAT');
      SUN:Observable<string> = this.translate.get('CALENDAR.SUN');
    
    
    
      daysOfWeeks:string[] = [`${this.MON}`, `${this.TUE}`, `${this.WED}`, `${this.THU}`, `${this.FRI}`, `${this.SAT}`, `${this.SUN}`];

 constructor(
      public translate: TranslateService
    ) { }

HTML:

 <div *ngFor="let day of daysOfWeeks">{{ day | async}}</div>

我也试过直接在 ngFor 中使用管道,但还是不行。

我将分享两种解决这个问题的方法。

1- 你可以使用 translateService.instant

instant(key: string|Array, interpolateParams?: Object): string|Object: Gets the instant translated value of a key (or an array of keys). /!\ This method is synchronous and the default file loader is asynchronous. You are responsible for knowing when your translations have been loaded and it is safe to use this method. If you are not sure then you should use the get method instead.

像这样

//for single
    const traslateSingle :string =  this.translateService.instant("Monday"); // translated "Monday"

//for list
    const transaletedList = ["Monday", "Tuesday", "Wednesday"].map(x=> this.translateService.instant(x)) // translated Week days

但它有自己的问题 如果没有加载翻译怎么办? 如果语言选择发生变化怎么办,现在您有责任获取更新的翻译

2- 在 component.html

中使用 translate 管道
const daysOfWeeks = ["Monday", "Tuesday", "Wednesday"]
 <div *ngFor="let day of daysOfWeeks">{{ day | translate}}</div>

它负责自动翻译文本并检测语言更改然后重新翻译。

所以它是解决您问题的更好方法。