Passing data from child to parent component ( child loaded via routing)

北城余情 提交于 2019-12-09 03:39:28

问题


I have this issue.

Chat is a parent component and it has Messages child component. I have url-s, /chat/, /chat/:id. So i can get :id param in Messages component with RouteParams, but i need that :id in Chat component. So if i load /chat/46 then Chat component knows that 46 :id

If i am loading it as directive something like <messages (Event)="handleEvent()"></messages> than i can pass it via EventEmitter and Output, but if i load component through <router-outlet> how i can pass value back to the parent ? EventEmitter and Output doesn't work in this case. Maybe there is something in router that can do the trick.


回答1:


You can do this by interaction between components as suggested. Here is an example:

component-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();
}

This way the id changes are subscribed and parent can preety much get it every time.

EDIT: Changed the EventEmitter to Subject and asObservable combo as advised by Angular team and added unsubscribe to avoid memory leak.




回答2:


You should consider to use Dependency Injection to inject a SessionService instance (always the same instance) both in Chat (parent) and Message (Child).

When the Child has a value to communicate to the Parent it can store it into the SessionService; if the SessionService instance is the same (which is granted by standard Dependency Induction use) than the Parent should be able to catch what Child wants to communicate.

I hope it helps



来源:https://stackoverflow.com/questions/37147826/passing-data-from-child-to-parent-component-child-loaded-via-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!