[英]Not able to understand parent child communication
據我所知,對於父子通信,有很多裝飾器,例如 @Input、@Output、@ViewChild 和許多其他方法,但是在回答一個問題時,我遇到了下面的問題,現在我無法理解它
App.component.ts(父級)
import { Component } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
parentVariable = 'parentTesting'
// constructor(private childComp: ChildComponent) { // Giving error
// console.log(this.childComp)
// }
}
應用程序組件.html
<h1>Parent</h1>
<child></child>
子組件.ts
import { Component, Input } from '@angular/core';
import { AppComponent } from './app.component';
@Component({
selector: 'child',
templateUrl: './child.component.html',
styles: [`h1 { font-family: Lato; }`]
})
export class ChildComponent {
childVariable = 'childTesting'
constructor(private appComp: AppComponent) {
console.log(this.appComp) // This is working
}
}
在構造函數中的子組件中,我正在獲取 AppComponents 實例,但是如果我在 Appcomponent 的構造函數中做同樣的事情,則會出現致命錯誤。
你能告訴我這背后的邏輯嗎
這是一個循環引用問題,導致Can't resolve all parameters for ChildComponent: (?).
錯誤。
這就是為什么:
您正在嘗試構造AppComponent ,因此您調用了構造函數。
構造函數需要先構造ChildComponent再提供,因此現在調用ChildComponent 的構造函數。
而ChildComponent 的構造函數需要AppComponent ,即尚未構造的(?)
參數,等待它完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.