【问题标题】:ngx-translate: use with interfaces, *ngFor and switchngx-translate:与接口、*ngFor 和 switch 一起使用
【发布时间】:2021-03-30 01:41:17
【问题描述】:

我被分配了使用 ngx-translate 在 Angular 中翻译侧边栏的职责。要翻译的元素是一个接口,表示授予的用户类型

export interface userType {
 role: [string, string];
 operations: [string, string, string][];
}

为了知道用户的类型,我们在 componets.ts 中放置了一个 switch 条件

switch(typeOfUser) {
case 'ROLE_CLIENT':
(() => {
this.userType = {
role: ['EnglishStr', 'EnglishStr'],
operations: ['EnglishStr', 'EnglishStr', 'EnglishStr']
}})}

我已经翻译了 es.json 文件中的字符串,但字面意思是逐字翻译。

"EnglishStr": "SpanishStr"

现在,在 component.html 中,我们确实有一个 *ngFor 来遍历 userType.operations

    <li *ngFor="let string of userType.operations">
      <a routerLink="{{ string[2] }}">
        <i class="{{ string[0] }} me-3"></i>
        <span> {{ string[1] | translate}} </span>
      </a>
    </li>

虽然翻译管道完成了我被要求的工作:有没有更好的方法来解决这个问题?
我在 es.json 中尝试过这种方式

userType : {
role: ['SpanishStr', 'SpanishStr'],
operations: ['SpanishStr', 'SpanishStr', 'SpanishStr'] }

没有从英语翻译成西班牙语。为什么我的第一种方法不正确?与我使用的方法不同吗?非常感谢

【问题讨论】:

  • string 是保留变量类型。永远不要将变量命名为string。我很惊讶你的编译器没有在这里报告错误。
  • With no result 是什么意思?你得到的输出是什么,你期望的输出是什么?
  • 你是对的,但我不在项目的那个部分。许多人在甲板上。是的,编译器根本没有给出任何警告。Lynx242
  • 阅读 ngx-translate 文档时,它解释了将数据放置在 json 文档中的不同方式。当我使用上述方法时,ngx-translate 没有从英语翻译成西班牙语。然后,当一个字一个字地写下来时,达到预期的效果并毫无问题地翻译它。这意味着我的第一种方法不正确Lynx242

标签: angular ngx-translate


【解决方案1】:

好吧,我浏览了 ngx-translate 文档。根据您在此处描述的方法,我找不到任何提示。我必须补充一点,我在不同的项目中使用了 ngx-translate 好几年了。

翻译者的目标始终是拥有一个标识符字符串,然后您可以通过该字符串进入当前激活语言的 JSON 文件并搜索匹配的翻译。

在您的示例中,您有

en.json

{
   "name": "name",
   "age":  "age"
}

es.json

{
   "name": "nombre",
   "age": "edad"
}

然后 UI 将显示此标识符的英语或西班牙语字符串表示形式。

没有办法。

为了更明显,您可以使用更具体的标识符,例如

en.json

{
   "global.name": "name",
   "global.age":  "age",
   "xyz.component.direction": "direction",
   "abc.component.working-hours": "working hours"
}

es.json

   "global.name": "nombre",
   "global.age":  "edad",
   "xyz.component.direction": "dirección",
   "abc.component.working-hours": "horas laborales"

【讨论】:

  • Lynx242 非常感谢。由于这是我第一次使用 ngx-translate,我认为这是我缺乏经验/知识,不知道如何在 *ngFor 中使用 ngx-translate。
  • 没问题。我不确定你的问题的目的可能是什么。现在很清楚了。 ;)
  • PS:如果您发现我的解释有用,如果您将其标记为您问题的解决方案,我将不胜感激。提前谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 2018-04-01
  • 2019-02-09
  • 2021-05-29
相关资源
最近更新 更多