[英]Passing data from child to parent component ( child loaded via routing)
我有這個問題。
聊天是父組件,它具有Messages子組件。 我有url -s, /chat/
, /chat/:id
。 所以我可以得到:id
帶有RouteParams的 Messages組件中的:id
param,但我需要:id
Chat組件中的:id
。 所以,如果我加載/chat/46
那么Chat組件知道46 :id
如果我將它作為指令加載,如<messages (Event)="handleEvent()"></messages>
,我可以通過EventEmitter和Output傳遞它,但如果我通過<router-outlet>
加載組件我怎么能通過價值回到父母? 在這種情況下,EventEmitter和Output不起作用。 也許在路由器中有一些東西可以做到這一點。
您可以通過建議的組件之間的交互來完成此操作。 這是一個例子:
組件interaction.service.ts
id = new Subject<number>();
idEmitter$ = this.id.asObservable();
sendId(id:number){
this.id.next(id);
}
messages.component.ts
constructor(private router:Router, private cci:ComponentInteractionService){}
ngOnInit(){
this.cci.sendId(this.router.param); // sending your params the way you get it
}
chat.component.ts
id:number;
subscription: Subscription;
constructor(private cci:ComponentInteractionService){}
ngOnInit(){
this.subscription = this.cci.idEmitter$.subscribe(res =>this.id = res);
}
ngOnDestroy(){
this.subscription.unsubscribe();
}
這樣就可以訂閱id更改,並且父母每次都可以更好地獲取它。
編輯:根據Angular團隊的建議將EventEmitter更改為Subject和asObservable組合,並添加取消訂閱以避免內存泄漏。
您應該考慮使用依賴注入在Chat(父)和Message(子)中注入SessionService實例(始終是相同的實例)。
當Child具有與Parent通信的值時,它可以將其存儲到SessionService中; 如果SessionService實例是相同的(由標准的Dependency Induction使用授權),那么Parent應該能夠捕獲Child想要通信的內容。
我希望它有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.