angular - 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 的打字稿来获取翻译文本?
解决方案
@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 中使用分开的“fileReplacements”。不显示所有 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",
...
}
}
推荐阅读
- angular6 - 如何卸载 Angular 打包库
- android - BLE 应用程序应始终在后台运行
- ibm-mobilefirst - IBM MFP 8 的单元测试 - Javascript 适配器
- bash - mv !(old-project) old-project 做什么?
- php - 合并多个 csv 文件产生空白 csv
- c# - c#异步更新http然后保存到本地数据库WhenAll ContinueWith时间
- r - 使用 selectInput 从 R Shiny 中的数据下载多个变量的问题
- php - 在 WooCommerce 存档页面上将产品变体显示为商店
- kdb - 在 q kdb 中读取超过 100 列的 csv 文件
- c# - 如何创建一个类似于现有枚举的枚举在第一个定义更改时出现编译错误?