我有一个使用类型的 Angular 组件,在一种情况下获取一个数据而在另一种情况下获取另一个数据是一个易于阅读的解决方案是什么?
该组件也可以分为两个组件,即电话组件和电子邮件组件,但大多数逻辑尽管很小,但都会重复。
var getContactInfo, hasContactInfo;
if(type === 'email') {
getContactInfo = function (profile) { return profile.getEmail()};
hasContactInfo = function (profile) { return profile.hasEmail()};
} else if(scope.type === 'phone') {
getContactInfo = function (profile) { return profile.getPhone()};
hasContactInfo = function (profile) { return profile.hasPhone()};
}
我可能会使用一个对象来映射方法,具体取决于类型:
const buildContactInfo = (getContactInfo, hasContactInfo) => ({ getContactInfo, hasContactInfo });
const contactInfoByType = {
email: buildContactInfo((profile) => profile.getEmail(), (profile) => profile.hasEmail()),
phone: buildContactInfo((profile) => profile.getPhone(), (profile) => profile.hasPhone())
};
然后,在调用时:
const contactInfo = contactInfoByType[type];
if (!contactInfo) {
throw new Error(`No contact info matched type '${type}'`);
} else {
contactInfo.hasContactInfo(profile);
contactInfo.getContactInfo(profile);
}