加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

有角度 – 如何将父组件注入子组件?

发布时间:2020-12-17 07:47:18 所属栏目:安全 来源:网络整理
导读:我试图将一个父组件注入一个子组件.我以为这是直截了当的 – 只需指定/注入孩子的构造函数()中的父组件: constructor(private _parent:AppComponent) {} // child component constructor 我收到以下错误: EXCEPTION: Cannot resolve all parameters for Ch
我试图将一个父组件注入一个子组件.我以为这是直截了当的 – 只需指定/注入孩子的构造函数()中的父组件:
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(); }
}

Plunker

参见@ 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读