首页 > 解决方案 > Angular @Optional 指令注入被忽略

问题描述

我收到这样的错误

Can't resolve all parameters for ControlErrorsDirective: (?, [object Object], [object Object], [object Object], [object Object], ?).

有服务声明。

    constructor(
        @Optional() @Host() private form: FormSubmitDirective,
        private control: NgControl,
        private resolver: ComponentFactoryResolver,
        public viewContainerRef: ViewContainerRef,
        @Inject(FORM_ERRORS) private errors,
        @Optional() controlErrorContainer: ControlErrorContainerDirective
      ) {

我看到注入问题与可选指令服务有关。是的,指令没有设置到组件中。但它们是可选的。为什么会调用错误?是的,我向模块提供了所有指令。

@NgModule({
  declarations: [
    AppComponent,
    ControlErrorsDirective,
    ControlErrorContainerDirective,
    FormSubmitDirective,
    ControlErrorComponent
  ],
  entryComponents: [
    ControlErrorComponent
  ],

但它不起作用。这个错误似乎微不足道。但我没有看到它。在这里效果很好。https://stackblitz.com/edit/angular-terms-and-conditions-reactive-forms?embed=1&file=src/app/form-errors.ts 问候。

标签: angular

解决方案


诸如此类的错误:

无法解析Something的所有参数:(?,

通常意味着在执行装饰器时,构造函数中用于参数的类型是未定义的。

它可能发生的原因有几个:

  • 您在 DI 中使用的类之间存在循环依赖关系

  • 您将所有类都放在一个文件中,并在声明之前尝试使用类型。所以顺序很重要。

在您的情况下,您将所有类都写在一个文件中,但尝试使用FormSubmitDirectiveand ControlErrorContainerDirectivebefore ControlErrorsDirectiveclass 这是您问题的主要原因。


推荐阅读