Angular typescript中的角度2和i18n

Angular typescript中的角度2和i18n,angular,typescript,internationalization,Angular,Typescript,Internationalization,我看到angular2为其组件实现了i18n,通过使用i18n(及其所有相关属性,如i18n title、复数等),您可以国际化html模板 但我想知道如何将typescript代码提供的字符串国际化。例如,我有一个弹出窗口,根据后端抛出的错误,我在其中打印不同的消息。该消息是由绑定到我的模板的变量提供的,我没有找到angular2国际化的方法来翻译该文本 更好理解的快速示例: typescript: errorMessage: string = ''; private errorMapp

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

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

更好理解的快速示例:

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

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

 template:
 <pop-up>{{errorMessage}}</pop-up>
typescript:
errorMessage:string='';
私有错误映射:Map;
onError(错误):无效{
this.errorMessage=errorMapping.get(error.code);
}
模板:
{{errorMessage}}
有办法吗

如果不是的话,是我以一种糟糕的方式实现了它吗?我应该换一种方式吗


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

这是一个老问题,但Angular 5仍然不支持这一点,与最初的提问者一样,我也试图避免使用第三方库,我的解决方法如下

  • 定义一个名为TranslationService的服务类,它有一个公共方法来接受翻译的键值映射,还有另一个公共方法来检索给定键的翻译
  • 在您的html输入页面,即
    app.component.html
    ,为您可能希望在应用程序中的任何位置通过编程访问的每个翻译添加一个
    ,即

    已存在具有此名称的邮件

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

    .translation{display:none;}

  • 使用Angular的本机i18n支持为您在上面定义的跨距定义所需的翻译,就像您在应用程序的任何html文件中对任何可翻译文本所做的那样

  • 在你的
    app.component.ts
    中,你可以绑定到你在html中定义的翻译,从中获取文本,并建立一个可以传递到翻译服务的翻译地图。由于这是在entry组件中完成的,因此应用程序中需要访问其中一个翻译的任何组件都可以使用它。代码如下:

    @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);
      }
    }
    
    @组件({
    选择器:'应用程序根',
    templateUrl:“./app.component.html”,
    样式URL:['./app.component.css']
    })
    导出类AppComponent实现OnInit{
    @ViewChild('error_1200')error1200:ElementRef;
    构造函数(私有TranslationService:TranslationService){}
    恩戈尼尼特(){
    让translations=newmap();
    translations.set('error_1200',
    这是.error1200.nativeElement.textContent);
    this.translationService.setTranslations(translations);
    }
    }
    
  • 应用程序中的任何组件都需要这些翻译,只需插入翻译服务,并使用相应的键检索所需内容即可


  • 我建议使用ng2-translate。感谢您的建议,但我更喜欢官方angular实现,而不是第三方库。有,但它不连接到XLF文件中的消息,后者用于i18n的其余部分。第三方解决方案之所以存在,是因为Angular i18n支持非常有限,而且路线图也不太有希望。请查看我的答案