【问题标题】:Angular: How to resolve circular dependency between directive and component?Angular:如何解决指令和组件之间的循环依赖?
【发布时间】:2017-08-23 07:58:18
【问题描述】:

我有一个 RadioButtonComponent 和一个 RadioButtonGroupDirective,它们相互依赖:

单选按钮组件:

import { RadioButtonGroupDirective } from "./radio-button-group.directive";
...
constructor(@Optional() @Inject(forwardRef(() => RadioButtonGroupDirective)) radiobuttonGroup: RadioButtonGroupDirective, ...) {

RadioButtonGroupDirective:

import { RadioButtonComponent } from "./radio-button.component";
...
@ContentChildren(forwardRef(() => RadioButtonComponent))
private radioButtons: QueryList<RadioButtonComponent>;

使用 angular-cli 中的最新 webpack 更新,我在构建时收到以下警告:

WARNING in Circular dependency detected:
lib\controls\radio-button\radio-button-group.directive.ts -> lib\controls\radio-button\radio-button.component.ts -> lib\controls\radio-button\radio-button-group.directive.ts

WARNING in Circular dependency detected:
lib\controls\radio-button\radio-button.component.ts -> lib\controls\radio-button\radio-button-group.directive.ts -> lib\controls\radio-button\radio-button.component.ts

事实上,代码之所以有效,是因为我在这两种情况下都使用了forwardRef(),指定另一个类可能尚未加载。但是我该如何解决这个警告呢?

通常,我会为两个类之一实现一个接口并使用它,但@Inject@ContentChildren 都不能使用接口,对吧?

【问题讨论】:

  • 如果有 RadioButtonGroup,我必须将 RadioButton 的某些输入事件委托给它。但这甚至有什么不同吗?如果我使用@Input,我仍然需要对指令的引用...
  • 你是如何结合使用这两个东西的?每次使用按钮时,指令是否应用于按钮(或按钮组?)?或者它并不总是一对一的。或一对多。在不知道的情况下很难回答,但我会说几乎没有使用 forwardRef 解决循环依赖的实例是一个很好的长期解决方案。

标签: angular dependency-injection circular-dependency


【解决方案1】:
  1. 按目的排列 您的 文件结构

  2. 为每个文件夹组添加一个 index.ts 文件。

  3. 在 index.ts 中,导出您的模块、组件、文件夹和/或等。

例如 内部组件/shared/buttons/index.ts

export * from './radiobuttoncomponent';

在单选按钮文件夹之外 添加另一个 index.ts export * from './radiobutton';

在您的导入中更新引用以使用通用路径

import { RadioButtonComponent} from "./shared";

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2012-03-15
    • 2016-09-21
    相关资源
    最近更新 更多