微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Angular 中应用依赖倒置原则?

如何解决如何在 Angular 中应用依赖倒置原则?

让我们考虑以下场景: 您在登录表单中有一个用于密码恢复的按钮,此操作将打开一个带有两个选项的模式:“通过 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 举报,一经查实,本站将立刻删除。