作者:这个世界我看不懂2011_595 | 来源:互联网 | 2022-12-04 13:45
我看到angular6为其组件实现了i18n,并且通过使用i18n可以将html国际化,但是您可以对打字稿做同样的事情吗?我有两个特定领域
zingchart中的一个:-能够进行示例
exampleData = {
valueBox: {
text: '%pie-total-value
Example',
placement: 'center',
fontWeight: 'normal'
},
}
非常感谢您的时间和答复。
1> Mir-Ismaili..:
直到现在(@angular/language-service v7.2
),都无法通过库的API进行此操作。
以下是我的解决方法(感谢fredrikredflag 在GitHub上的出色文章,并感谢@BrunoBruzzano的链接):
src/app/i18n.service.ts
:
import {Injectable} from "@angular/core";
import {Xliff2} from '@angular/compiler';
// You can also import {Xliff} or {Xtb} instead of {Xliff2}, depending on your project configurations
declare const require;
const cOntent= require('raw-loader!../i18n/messages.fa.xlf');
@Injectable({
providedIn: 'root'
})
export class I18nService {
private readonly xliff: any = new Xliff2().load(content, '');
get(key: string): string {
return this.xliff.i18nNodesByMsgId[key][0].value;
}
}
i18n伪组件(仅用于messages.xlf
文件中的自动生成翻译):
src/app/i18n/i18n.component.ts
(不重要。只需要存在即可。):
import {Component} from '@angular/core';
@Component({templateUrl: './i18n.component.html'})
export class I18nComponent {}
src/app/i18n/i18n.component.html
(别忘了使用id!)
New version available. Load New Version?
别忘了I18nComponent
在您的邮件中声明@NgModule
。
用法(运行ng xi18n ...
和翻译后):
在您的组件中:
import {Component} from '@angular/core';
@Component({templateUrl: './i18n.component.html'})
export class I18nComponent {}
i18n.service.ts
在构建之前要翻译的实用程序脚本:
(此要求:require('raw-loader!../i18n/messages.fa.xlf')
需要进行翻译以匹配所需的语言环境。)
PreBuild/prebuild.ts
:
New version available. Load New Version?
PreBuild/tsconfig.json
:
{
"compilerOptions": {
"outDir": "./build",
"lib": [
"es2018",
"dom"
],
"module": "commonjs",
"moduleResolution": "node",
"target": "es6",
"typeRoots": [
"../node_modules/@types"
]
},
"files": [
"prebuild.ts"
]
}
package.json
:
...
"scripts": {
"compile-pre-build": "tsc -p PreBuild/tsconfig.json --pretty",
"pre-build": "node PreBuild/build/prebuild.js",
...
...
用法:
(一次过npm run compile-pre-build
:)
...
import {I18nService} from './i18n.service';
...
constructor(private i18nService: I18nService, ...) { ... }
sampleUsage() {
confirm(this.t('newVersionAlert'));
}
/**
* translate
*/
private t(i18nId: string) {
return this.i18nService.get(i18nId);
}
...
要么
import {Xliff2} from "@angular/compiler";
// You can also import {Xliff} or {Xtb} from "@angular/compiler" depending of your case.
const fs = require('fs');
const path = require('path');
const localeId = process.argv[2];
if (localeId === undefined) throw new Error(`No language specified.\nUsage: node ${path.basename(__filename)} '}`);
const cOntent= fs.readFileSync(`src/i18n/messages.${localeId}.xlf`, 'utf8');
const xliff = new Xliff2().load(content, '');
const i18nServiceFilePath = './src/app/i18n.service.ts';
fs.writeFileSync(i18nServiceFilePath,
fs.readFileSync(i18nServiceFilePath, 'utf8')
.replace(/(raw-loader!\.\.\/i18n\/messages\.)\w{2}(\.xlf)/, `$1${xliff.locale}$2`)
);
这将进行编辑i18n.service.ts
。