【问题标题】:Injecting ngControl in custom validator directive, causes cyclic dependency在自定义验证器指令中注入 ngControl,导致循环依赖
【发布时间】:2017-02-10 01:38:56
【问题描述】:

我正在尝试创建自定义 angular 2 验证器指令,它像这样注入 NgControl:

@Directive({
  selector: '[ngModel][customValidator]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
})
export class CustomValidatorDirective implements Validator {
  private validateFunction: ValidatorFn;

  constructor(private control: NgControl) { };

}

但我收到以下错误:

无法实例化循环依赖! NgControl

有谁知道我如何解决它,以便在初始化后访问 ngControl?

【问题讨论】:

  • 你用的是哪个版本?
  • 版本为2.0.0
  • 你能从这里删除 providers 部分并将其添加到 @NgModel({}) 中吗?
  • 感谢@micronyks,看来这解决了问题。

标签: angular angular2-directives


【解决方案1】:

Providers, Pipes, Directives 声明已从 @Component@Directive 中删除RC6RC7 之后的 装饰器。所以你只需要删除

providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}] 

来自指令

并将其添加到 @NgModule({}) 装饰器

@NgModule({
 ...
 providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]

})

【讨论】:

  • @yurzui 感谢分享。那么问题可能是不在这里提供这样的提供者配置。或者可能在这里提供提供者可能会创建其他实例或其他东西。
  • 我认为将提供者注册放在 NgModule 而不是指令中会导致验证器在可以访问 CustomValidatorDirective 的模块之间共享。显然,当其他指令也使用它时,它会污染 NG_VALIDATORS。
【解决方案2】:

您可以通过 Injector 注入 NgControl 以避免循环依赖。

constructor(private _injector: Injector) { }

ngOnInit() {
  console.log(this._injector.get(NgControl))
}

【讨论】:

  • injector.get(NgControl) 好像贬值了。请参阅 this 了解替代解决方案。
猜你喜欢
  • 1970-01-01
  • 2019-10-30
  • 2013-07-14
  • 1970-01-01
  • 2022-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
相关资源
最近更新 更多