gpt4 book ai didi

angular - 如何将父组件注入(inject)子组件?

转载 作者:太空狗 更新时间:2023-10-29 16:48:25 26 4
gpt4 key购买 nike

我正在尝试将父组件注入(inject)子组件。我认为这很简单——只需在 child 的 constructor() 中指定/注入(inject)父组件:

constructor(private _parent:AppComponent) {}   // child component constructor

我收到以下错误:

EXCEPTION: Cannot resolve all parameters for ChildComponent(?). Make sure they all have valid type or annotations.

我错过了什么?

子组件:

import {Component} from 'angular2/core';
import {AppComponent} from './app.component';

@Component({
selector: 'child',
template: `<p>child</p>`
})
export class ChildComponent {
constructor(private _parent:AppComponent) {}
}

应用组件:

import {Component} from 'angular2/core';
import {ChildComponent} from './child.component';

@Component({
selector: 'my-app',
template: `{{title}} <child></child>
`,
directives: [ChildComponent]
})
export class AppComponent {
title = "Angular 2 - inject parent";
constructor() { console.clear(); }
}

Plunker

最佳答案

参见@EricMartinez 的 comment的答案。问题似乎是 A 导入 B 和 B 导入 A 时的循环引用。

这是一个 plunker使用两个文件而不是 Eric's plunker 中的一个文件.

我原来的 plunker 的唯一变化是在 ChildComponent 中:

import {Component, Inject, forwardRef} from 'angular2/core';
// ....
constructor(@Inject(forwardRef(() => AppComponent)) private _parent:AppComponent)

我不确定这是否消除了循环引用,因为 A 和 B 仍在相互导入,但它似乎有效。

另见 https://github.com/angular/angular/issues/3216 ,其中 Miško 指出:

This [not user-friendly declaration using forwardRef()] is a limitation of JS and how the function declarations get hoisted. Whenever you have a circular dependency you will need forwardRef :-( I just don't see a away around it.

I would argue that you should not be in situation where your parent needs to know about the children and children need to know about parent. @Query should take care of most of the use cases.

I am sorry, but while I agree this is a pain in some rare cases, I don't see a way out of it, and hence this issue is not actionable, will close.

嗯...我尝试注入(inject) parent 的原因是因为我看到 child 与 parent 交流的两种方式:

  1. 子级定义输出属性并发出父级订阅的事件
  2. 子级注入(inject)父级(例如,Pane 可能注入(inject) Tabs)然后可以调用父级的方法

我试图确定何时使用每种方法。 Miško 让它听起来像 2. 应该很少见。

更新: 我在考虑更多... 1. 更好,因为 child 和 parent 之间的耦合较少。 1. child 不需要知道(并且可能不应该知道) parent 的公共(public) API/接口(interface)。
在相反的方向(例如,父级使用@ViewChild(@Query 现已弃用)获取对子级的引用,然后调用方法子),耦合很好,因为父组件正在使用子组件,所以它需要知道子组件的公共(public) API/接口(interface):即输入和输出属性以及公共(public)方法。

关于angular - 如何将父组件注入(inject)子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34540615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com