typescript 中的 Angular 2 和 i18n

标签 angular typescript internationalization

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

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

更好理解的快速示例:

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

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

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

有办法吗?

如果不是,我是不是以糟糕的方式实现它的人?我应该采取不同的做法吗?

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

最佳答案

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

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

    <span class="translation" #error_1200 i18n="@@error_1200">A Message already exists with this Name</span>

  3. 在你的app.component.css , 添加以下内容,这样您上面定义的静态翻译列表实际上不会在浏览器中显示

    .translation {display: none;}

  4. 使用 Angular 的原生 i18n 支持,以您对应用程序中任何 html 文件中的任何可翻译文本所做的正常方式,为您在上面定义的跨度定义所需的翻译。

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

    @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. 无论您应用中的哪个组件需要这些翻译之一,只需注入(inject)您的翻译服务并使用它通过适当的 key 检索您需要的内容

关于 typescript 中的 Angular 2 和 i18n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41182055/

相关文章:

angular - 如何正确设置新的 Angular 6 项目

angular - Angular 2 中的单例服务

Android 应用显示不正确的西类牙口音字符

javascript - Nativescript Angular : Can't read object from inside a function (this. 未定义?)

qt - 用于 QT 国际化的 Pyside 的 .pro 文件

internationalization - 不同语言的国名的好来源? (用于多语言形式)

angular - 上传 PUT 请求由 Angular ServiceWorker 发送两次

validation - Angular 2,带参数的自定义验证消息

angular - 即使启用了 gzip 压缩,Nginx 服务器也不会读取 Gzip 文件

typescript - 如何使用 Mocha 测试 Typescript 中的类是否抽象?