问题描述
让我们考虑以下场景: 您在登录表单中有一个用于密码恢复的按钮,此操作将打开一个带有两个选项的模式:“通过 SMS 恢复”和“通过电子邮件恢复”,根据选择的选项,该表单允许您输入文本以键入电子邮件或手机和发送恢复请求的按钮。
在 Angular 中,您可以创建一个服务,将所选方法作为参数,并根据该参数执行恢复密码的操作。 但是,如果添加更多方法,则需要放置更多条件才能做出正确的请求。 根据 SOLID 原则,您应该依赖抽象而不是细节,这就是为什么您可以执行以下操作:
const regexString = `${keyword}`;
const regex = new RegExp(regexString);
const matches = ['firstName',other fields here .. ].map(field => ({
[field]: { $regex: regex,$options: 'i' },}));
const data = await Users.find(
{
$and: [
{
userId,},{ $or: matches },],);
和组件:
export interface RecoveryRepository {
recoveryPassword(userId: string): void;
}
@Injectable()
export class SMSRepositoryService implements RecoveryRepository {
recoveryPassword(userId: string): void{
// sms implementation
}
}
@Injectable()
export class EmailRepositoryService implements RecoveryRepository {
recoveryPassword(userId: string): void{
// email implementation
}
}
@Injectable()
export class OtherRepositoryService implements RecoveryRepository {
recoveryPassword(userId: string): void{
// any other implementation
}
}
然后为了使用 SMS 实现,我应该在组件中定义一个提供程序:
@Component({
selector: 'app-modal-recovery',templateUrl: './modal-recovery.component.html'
})
export class ModalRecoveryComponent {
constructor(
private _formBuilder: FormBuilder,private recoveryRepository: RecoveryRepository
) {
/*
.
.
modal form deFinition with FormBuilder
.
.
*/
}
public recovery() {
}
}
或电子邮件:
@Component({
selector: 'app-modal-recovery',templateUrl: './modal-recovery.component.html',providers: [{ provide: RecoveryRepository,useClass: SMSRepositoryService }]
})
然后调用方法:@Component({
selector: 'app-modal-recovery',useClass: EmailRepositoryService }]
})
但是,如果表单中的恢复方法值是动态的,那么我如何根据用户选择的是短信还是电子邮件选项来更改存储库实例?
this.recoveryRepository.recoveryPassword();
但它违反了 SOLID 原则,而且如果我们考虑更复杂的场景,我们可能需要更改组件中的许多内容。那么就有可能有一种工厂负责根据选择的选项更改实例并使用 this.recoveryRepository.recoveryPassword(userId) 并且仅依赖于抽象类
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)