打字稿中的Angular 6和i18n [英] Angular 6 and i18n in typescript

查看:98
本文介绍了打字稿中的Angular 6和i18n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到angular6为其组件实现了i18n,并且通过使用i18n可以使html国际化,但是您可以对打字稿做同样的事情吗?我有两个特定领域

I saw that angular6 implements i18n for its components and that by using i18n you can internationalize your html but can you do the same with typescript? I have two specific areas

一个有趣的图表:-能够举个例子

One in a zingChart: - Be able to i18n Example

exampleData = {
 valueBox: {
                text: '<span style="font-size: 32px">%pie-total-value</span> <br/> Example',
                placement: 'center',
                fontWeight: 'normal'
            },
     }

非常感谢您的时间和回答.

Thank you very much for your time and answers.

推荐答案

直到现在(@angular/language-service v7.2),都无法通过库的API进行此操作.

This is not possible through the library's API until now (@angular/language-service v7.2).

下面是我的解决方法(感谢fredrikredflag 他在GitHub上的好帖子感谢@BrunoBruzzano提供的链接):

Below is my workaround (thank fredrikredflag for his good post on GitHub and thank @BrunoBruzzano for the link):

src/app/i18n.service.ts :

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文件中的自动生成翻译):

i18n pseudo-component (JUST FOR AUTO-GENERATING TRANSLATIONS in messages.xlf file):

  1. src/app/i18n/i18n.component.ts (无关紧要.只需要存在即可).

  1. src/app/i18n/i18n.component.ts (Isn't important. Just needed to exists.):

import {Component} from '@angular/core';
@Component({templateUrl: './i18n.component.html'})
export class I18nComponent {}

  • src/app/i18n/i18n.component.html ( 不要忘记使用ID! )

  • src/app/i18n/i18n.component.html (don't forget using an id!)

    <p i18n="@@newVersionAlert">New version available. Load New Version?</p>
    

  • 不要忘记在@NgModule中声明I18nComponent.

    用法(运行ng xi18n ...并翻译后):

    在您的组件中:

    ...
    import {I18nService} from './i18n.service';
    
    ...
        constructor(private i18nService: I18nService, ...) { ... }
    
        sampleUsage() {
            confirm(this.t('newVersionAlert'));
        }
    
        /**
         * translate
         */
        private t(i18nId: string) {
            return this.i18nService.get(i18nId);
        }
    ...
    


    实用脚本,可在构建前翻译i18n.service.ts :


    Utility script to translate i18n.service.ts before build:

    (此要求:require('raw-loader!../i18n/messages.fa.xlf')需要进行翻译以匹配所需的语言环境.)

    (This requirement: require('raw-loader!../i18n/messages.fa.xlf') needs to be translated to match wanted locale.)

    PreBuild/prebuild.ts :

    PreBuild/prebuild.ts:

    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)} <locale-id${'>'}`);  
    
    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`)  
    );
    

    PreBuild/tsconfig.json :

    PreBuild/tsconfig.json:

    {
        "compilerOptions": {
            "outDir": "./build",
            "lib": [
                "es2018",
                "dom"
            ],
            "module": "commonjs",
            "moduleResolution": "node",
            "target": "es6",
            "typeRoots": [
                "../node_modules/@types"
            ]
        },
        "files": [
            "prebuild.ts"
        ]
    }
    

    package.json :

    package.json:

    ...
    "scripts": {
        "compile-pre-build": "tsc -p PreBuild/tsconfig.json --pretty",
        "pre-build": "node PreBuild/build/prebuild.js",
        ...
    ...
    

    用法:

    (一次npm run compile-pre-build:)

    npm run pre-build -- fa
    

    npm run pre-build -- en
    

    这将编辑i18n.service.ts.

    这篇关于打字稿中的Angular 6和i18n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆