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

元气小坏坏 提交于 2019-12-01 20:32:31

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.

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

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