In my application I noticed unexpected behavior. Probably I made a mistake but I don't know where.
Scenario: I have two components: parent and child. Parent template contains '*ngIf' condition and can display or not child. Parent and child shares service. Child subscribes event. Parent emits event.
After series of below steps: 1. hide child 2. show child 3. trigger event
event is handle n+1 times. Where n is number of trials. Plunk for this example: https://plnkr.co/edit/TWHO6PPYa55QGoHDXdFN
Parent component template:
<div *ngIf="show">
<my-child-app></my-child-app>
</div>
Parent relevant class code:
show:boolean = true;
constructor(private service: AppService) {
}
changeShow(){
this.show = !this.show;
}
emitSome(){
this.service.appEvent.emit("abc");
}
Child relevant part of code:
constructor(private service: AppService) {
this.service.appEvent.subscribe((s: string) => console.log(s));
}
You need to clean up the subscription when the component is destroyed. Every time the child is shown because of the ngIf
it calls the constructor of the child which re-subscribes to the Emitter. Modify your code to match the following:
export class ChildComponent implements OnDestroy {
private eventSubscription;
constructor(private service: AppService) {
this.eventSubscription = this.service.appEvent
.subscribe((s: string) => console.log(s));
}
ngOnDestroy(){
this.eventSubscription.unsubscribe();
}
}