简体   繁体   English

Angular 2 i18n:动态反馈

[英]Angular 2 i18n: Dynamic feedback

I have an Angular 2 app that currently uses ng2-translate to manage multiple languages for the GUI. 我有一个Angular 2应用程序,当前使用ng2-translate管理GUI的多种语言。 It's communicating with a API that responds to requests using a combination of HTTP status codes and custom API codes. 它正在与使用HTTP状态代码和自定义API代码的组合来响应请求的API通信。

So I can for instance get this back on a HTTP call to it: 因此,例如,我可以通过HTTP调用将其返回:

{
    success = true,
    code = 'A00001'
}

I have a document that explains what "A00001" means, so I know what translation to load. 我有一个解释“ A00001”含义的文档,所以我知道要加载什么翻译。

Now, I want to make the switch to use Angular's own i18n solutions. 现在,我想切换到使用Angular自己的i18n解决方案。 Mainly because I want to use as few third-party libraries as possible, but most importantly because it offers better support on giving context to translations. 主要是因为我想使用尽可能少的第三方库,但最重要的是因为它在为翻译提供上下文方面提供了更好的支持。

Looking at the documentation for i18n on angular.io , it looks pretty straight forward, but the only thing that's holding me back is how I am going to handle the responses from the API. 在angular.io上查看i18n的文档,看起来很简单,但是唯一让我退缩的是如何处理来自API的响应。

Since all strings are replaced/translated during compilation, how can I retreive a translated string and show it only when I detect a specific code from the API? 由于所有字符串在编译过程中都会被替换/翻译,因此如何检索经过翻译的字符串并仅在从API中检测到特定代码时才显示它?

This is basically what I do now: 这基本上就是我现在要做的:

switch(response.code) {
    case 'A00001':
        feedback = this._translateService.instant('translationKey');
    break;
}

Then I present the feedback for the user in the GUI. 然后,我在GUI中为用户提供反馈。

How would one solve this using Angulars i18n solution? 如何使用Angulars i18n解决方案解决此问题?

I've been trying to figure this out myself. 我一直想自己弄清楚这一点。

A) What a co-worker did was just translate all strings on the DOM and have a service get these elements' html content, set display none ofcourse. A)同事所做的只是翻译DOM上的所有字符串,并让服务获取这些元素的html内容,而没有设置显示内容。

B) As an alternative, you could have a switch case on your DOM for all the possible errors and show accordingly using *ngIf. B)或者,您可以为所有可能的错误在DOM上添加一个切换用例,并使用* ngIf进行相应显示。

C) A combination of A and B, you can create this as a separate component + service. C)A和B的组合,您可以将其创建为单独的组件+服务。 Which you can use anywhere you need the dynamic error messaging - this way your compiled view won't always contain the unnecessary translation. 您可以在需要动态错误消息的任何地方使用它-这样,您的已编译视图将不会始终包含不必要的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM