【问题标题】:Angular 2 and i18n in typescript打字稿中的 Angular 2 和 i18n
【发布时间】:2017-05-02 02:41:28
【问题描述】:

我看到 angular2 为其组件实现了 i18n,并且通过使用 i18n(以及它的所有相关属性,如 i18n-title、复数等),您可以国际化您的 html 模板。

但我想知道如何将打字稿代码提供的字符串国际化。例如,我有一个弹出窗口,根据我的后端抛出的错误,我会在其中打印一条不同的消息。该消息由绑定到我的模板的变量提供,我没有找到使用 angular2 国际化的方法来翻译该文本。

更好理解的简单示例:

 typescript:
 errorMessage: string = '';
 private errorMapping: Map<number,String>;

 onError(error): void {
   this.errorMessage = errorMapping.get(error.code);
 }

 template:
 <pop-up>{{errorMessage}}</pop-up>

有办法吗?

如果不是我以一种糟糕的方式实施它吗?我应该采取不同的做法吗?

非常感谢您的时间和回答。

【问题讨论】:

  • 我建议使用 ng2-translate。
  • 感谢您的建议,但我更喜欢官方的 Angular 实现而不是第三方库。
  • i18nSelect pipe 但它没有连接到来自 XLF 文件的消息,这些消息用于 i18n 的其余部分。第三方解决方案之所以存在,是因为 Angular i18n 支持非常有限,而且路线图也不是很有希望。
  • 在这里查看我的答案stackoverflow.com/a/56075872/4399281

标签: angular typescript internationalization


【解决方案1】:

这是一个老问题,但 Angular 5 仍然不为此提供支持,并且像最初的提问者一样,我也试图避免使用 3rd 方库,我的解决方法如下......

  1. 定义一个名为 TranslationsService 的服务类,它有一个公共方法来接受翻译的键值映射,以及另一个公共方法来检索给定键的翻译。
  2. 在您的入口页面 html 中,即app.component.html,为您可能希望在应用程序的任何位置以编程方式访问的每个翻译添加一个&lt;span&gt;,即...

    &lt;span class="translation" #error_1200 i18n="@@error_1200"&gt;A Message already exists with this Name&lt;/span&gt;

  3. 在您的app.component.css 中,添加以下内容,以便您在输入时实际上不会在浏览器中显示上述定义的静态翻译列表

    .translation {display: none;}

  4. 使用 Angular 的原生 i18n 支持为您在上面定义的 span 定义所需的翻译,就像您对应用程序中任何 html 文件中的任何可翻译文本所做的那样。

  5. 在您的app.component.ts 中,您可以绑定到您在 html 中定义的翻译,从中获取文本并构建可以传递给您的翻译服务的翻译地图。由于这是在入口组件中完成的,因此它可以从应用程序中需要访问这些翻译之一的任何组件中获得。代码如下:

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      @ViewChild('error_1200') error1200 : ElementRef;
    
      constructor(private translationsService: TranslationsService) { }
    
      ngOnInit() {
        let translations = new Map<string, string>();
        translations.set('error_1200', 
            this.error1200.nativeElement.textContent);
        this.translationsService.setTranslations(translations);
      }
    }
    
  6. 您的应用程序中的哪些组件需要这些翻译之一,只需注入您的翻译服务并使用它使用适当的键检索您需要的内容

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2016-10-31
    • 2018-04-15
    相关资源
    最近更新 更多