【问题标题】:Angular 6 - How to extract translation from typescriptAngular 6 - 如何从打字稿中提取翻译
【发布时间】:2019-03-01 03:01:33
【问题描述】:

我使用的是 Angular 6,并且根据此处找到的文档设置了翻译处理:https://angular.io/guide/i18n

问题是文档没有解释如何使用打字稿获得翻译。

这里有一个类似的问题:Can I use Angular i18n to translate string literals in typescript code

但我不能使用该答案,因为它依赖于 ngx-translate,一旦 Angular 赶上,该答案将被弃用,请参阅 https://github.com/ngx-translate/core/issues/495

那么使用 Angular 6 i18n - 我将如何使用基于 id 的 typescript 获取翻译文本?

【问题讨论】:

    标签: angular typescript localization internationalization translation


    【解决方案1】:

    @Diemauerdk,文档没有解释如何使用打字稿进行翻译,因为这是不可能的。解决方法可以在多个 .ts 中进行翻译。那是

    //file locale-us.ts
    export const translation:any={
       greeting:"Hello World!",
       mainTitle:"The best Appliacion of the world"
    }
    //file locale-es.ts
    export const translation:any={
       greeting:"¡Hola Mundo!",
       mainTitle:"la mejor aplicación del mundo"
    }
    

    在你的 .ts 中你可以有一个管道

    import { Pipe, PipeTransform } from '@angular/core';
    import { translation } from '../../i18n/locale-us';
    
    
    @Pipe({ name: 'translation' })
    export class TranslationPipe implements PipeTransform {
        constructor() {}
        transform(value: string): string {
            return translation[value] || null;
        }
    }
    

    你可以在一个组件中使用你在构造函数中注入管道的地方

    constructor(private translate: TranslationPipe){}
    //And use like
    
    alert(this.translate.transform('greeting'));
    

    然后你可以在 angular.json 中使用分开的“f​​ileReplacements”。不显示所有 angular.json,否则必须添加 fileReplacement。你有一个fe.g.如果您下载文档 https://angular.io/guide/i18n#internationalization-i18n 的 i18n 示例,则可以这样做

      "configurations": {
    
       "production": {
            ...
        },
        "production-es": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }, //add this two lines
            {
              "replace": "src/i18n/locale-us.ts",
              "with": "src/i18n/locale-es.ts"
            }
          ],
          ...
          "outputPath": "dist/my-project-es/",
          "i18nFile": "src/locale/messages.es.xlf",
          ...
        },
        "es": {
          //And add this too
          "fileReplacements": [
            {
              "replace": "src/i18n/locale-us.ts",
              "with": "src/i18n/locale-es.ts"
            }
          ],
          ...
    
         "outputPath": "dist/my-project-es/",
          "i18nFile": "src/locale/messages.es.xlf",
          ...
        }
      }
    

    【讨论】:

    猜你喜欢
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2019-02-11
    • 2019-11-11
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多