我有一个使用类型的角度组件,什么是一个易于阅读的解决方案,在一个案例中获取一个数据而在另一个案例中获得另一个数据?
组件也可以分为两个组件,即电话组件和电子邮件组件,但大多数逻辑虽然很小,但都会重复。
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()};
}
答案 0 :(得分:1)
我可能会根据类型使用映射方法的对象:
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);
}