dependency-injection - 注入(inject)与子组件相同类型的父组件

标签 dependency-injection angular

在 Angular 2 中,子组件可以通过构造函数参数注入(inject)其父组件。示例:

@Component({...})
export class ParentComponent {
  ...
}

@Component({...})
export class ChildComponent {
  constructor(private parent: ParentComponent) { }
  ...
}

只要父项和子项属于不同类型,这种方法就很好用。

但是,另一个典型的用例是树结构,其中每个树节点显示为单独的组件。如果每个树节点组件都应该访问其父节点,我们应该怎么做?我试过这个:

@Component({...})
export class TreeNodeComponent {
  constructor(private parent: TreeNodeComponent) { }
...
}

但这会失败并出现以下运行时异常:

EXCEPTION: Cannot instantiate cyclic dependency!

我猜原因是 Angular 2 注入(inject)了组件本身而不是它的父组件。

即使它们属于同一类型,我如何告诉 Angular 注入(inject)组件的父组件?

笨蛋 https://plnkr.co/edit/ddvupV?p=preview

最佳答案

它是这样工作的

constructor(@SkipSelf() @Host() @Optional() parent: TreeNodeComponent) {}

Plunker

  • @SkipSelf() 是为了不让自己注入(inject),如果请求 TreeNodeComponent 则适用
  • @Host() 不要向上看宿主元素
  • @Optional() ??根节点没有父 TreeNodeComponent

另见 http://blog.thoughtram.io/angular/2015/08/20/host-and-visibility-in-angular-2-dependency-injection.html

关于dependency-injection - 注入(inject)与子组件相同类型的父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35707464/

相关文章:

c# - 如何为使用包装器的 Azure Functions 编写单元测试?

spring - 单例和原型(prototype) bean 有什么区别?

java - 使用 Guice 注入(inject)许多装饰实例——关于将 HessianServlet 与 Guice 混合

c# - 如何从 C# Core 中的 DI 获取可用的 IOptions 列表?

javascript - 如何将焦点设置在 Angular 2 下拉列表的第一个列表项上

angular - 如何在 Angular2 组件模板中引用 "this"?

jsf - 如果 @PostConstruct 失败,Bean 会被创建吗

javascript - index.js 没有做 index.ts 做的事情

Angular2 : How to subscribe to Http. post observable inside a service and a component properly?

Angular FormArray - AbstractControl 类型上不存在属性控件