我试图将一个父组件注入一个子组件.我以为这是直截了当的 – 只需指定/注入孩子的构造函数()中的父组件:
constructor(private _parent:AppComponent) {} // child component constructor
我收到以下错误:
EXCEPTION: Cannot resolve all parameters for ChildComponent(?). Make sure they all have valid type or annotations.
我失踪了什么
ChildComponent:
import {Component} from 'angular2/core'; import {AppComponent} from './app.component'; @Component({ selector: 'child',template: `<p>child</p>` }) export class ChildComponent { constructor(private _parent:AppComponent) {} }
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(); } }
参见@ EricMartinez的
comment的答案. A进口B和B进口A时,问题似乎是循环参考
这是一个plunker,使用两个文件,而不是Eric’s 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
原文链接:https://www.f2er.com/angularjs/143116.html