首页 > 解决方案 > Angular 6 - 如何从打字稿中提取翻译

问题描述

我正在使用 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 的打字稿来获取翻译文本?

标签: angulartypescriptlocalizationinternationalizationtranslation

解决方案


@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. 如果您下载文档的 i18n 示例https://angular.io/guide/i18n#internationalization-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",
      ...
    }
  }

推荐阅读