Passing data from child to parent component ( chil

2019-02-24 20:03发布

问题:

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