我在我的表单上重构一个需要i18n配置对象的datepicker控件。
我拥有的是这个
import {BaseControl} from './base-control';
export class DatePickerControl extends BaseControl<Date> {
controlType = 'datepicker';
locale: any = {
en: {
firstDayOfWeek: 1,
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December'],
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
dateFormat: 'dd/mm/yy'
},
nl: {
firstDayOfWeek: 1,
dayNames: ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'],
dayNamesShort: ['Zon', 'Maa', 'Din', 'Woe', 'Don', 'Vri', 'Zat'],
... You get it by now
},
fr: {
},
de: {
},
...
};
constructor(options: {} = {}) {
super(options);
}
}
我在另一个文件中读取配置并在模板中使用它:
get i18nConfig(): any {
let val = null;
if (this.filter instanceof DatePickerControl) {
const language = this.translateService.currentLang;
val = <DatePickerControl>(this.filter).locale[language];
}
return val;
}
<p-calendar *ngSwitchCase="'datepicker'" [formControlName]="filter.key [id]="filter.key" [locale]="i18nConfig" [dateFormat]="i18nConfig.dateFormat">
</p-calendar>
现在我想在单独的.xx.json
文件中维护所有配置对象。
我知道我可以使用类似下面的解决方案,但它有效,但我不喜欢。
import * as i18n_en from './control-translations/datepicker/datepicker.en.json';
import * as i18n_nl from './control-translations/datepicker/datepicker.nl.json';
import * as i18n_fr from './control-translations/datepicker/datepicker.fr.json';
export class DatePickerControl extends BaseControl<Date> {
...
getConfig(lang: string): any {
switch (lang) {
case 'nl':
return i18n_nl;
case 'fr':
return i18n_fr;
case 'en':
default:
return i18n_en;
}
}
...
}
理想情况下,我希望是这样的,但我认为不可能;
getConfig(lang: string): any {
return `./control-translations/datepicker/datepicker.${lang}.json`;
}
还有其他我不知道的解决方案是 SYNCHRONOUS 吗? 我真的不想让这段代码异步。如果没有其他办法,我将使用我以前不太喜欢的解决方案,它将不得不做出应有的...
提前谢谢!