import { CommonUtils } from '@farris/ui-common'; import { Injectable, LOCALE_ID, Inject, InjectionToken, Optional } from '@angular/core'; import { FARRIS_LOCALES } from './locales'; export const FARRIS_LOCAL_CUSTOM_DATA = new InjectionToken('自定义语言数据, 格式:{ "localeCode": { "name": "value" } }'); @Injectable({ providedIn: 'root' }) export class LocaleService { langData: any; constructor(@Inject(LOCALE_ID) public localeId: string, private utils: CommonUtils, @Optional() @Inject(FARRIS_LOCAL_CUSTOM_DATA) private localeData: any) { if (!localeId) { localeId = 'zh-CHS'; } // 合并语言资源 this.setLocaleData(localeData); } /** 获取语言资源 * path : 资源路径,如: * ``` * getResources('zh-CHS') // 返回所有中文语言资源 * getResources('zh-CHS.lookup') // 返回所有中文下帮助的资源 * ``` */ getResources( path = '') { if (path) { return this.utils.getValue(path, FARRIS_LOCALES); } return FARRIS_LOCALES; } getComponentOptions(ctrlName) { return this.langData[ctrlName]; } getValue(propertyName: string) { const val = this.utils.getValue(propertyName, this.langData); if (val) { return val; } else { console.warn(`Can\'t find language Data for the ${propertyName}`); } } /** 合并现有的多语资源 */ setLocaleData(localeData = null) { if (localeData) { // 解析得到提供的语言编码 const langCodes = Object.keys(localeData); langCodes.forEach((code: string) => { const resName = Object.keys(localeData[code]); resName.forEach(k => { this.appendLanguageResource(k, localeData[code][k], code); }); }); } this.langData = FARRIS_LOCALES[this.localeId]; if (!this.langData) { this.langData = FARRIS_LOCALES['zh-CHS']; } } private appendLanguageResource(key: string, data: any, lang: string = this.localeId) { if (!lang) { this.langData[key] = this.langData[key] || {}; this.langData[key] = Object.assign(this.langData[key], data || {}); } else { FARRIS_LOCALES[lang][key] = data || {}; } } }