Angular 组合 ngIf 和 EventEmitter 创建多个调用
Angular combine ngIf and EventEmitter creates multiple calls
在我的应用程序中,我注意到了意外行为。可能我犯了一个错误,但我不知道在哪里。
场景:我有两个组件:parent 和 child。
Parent模板包含'*ngIf'条件,是否显示child。
Parent 和 child 共享服务。 Child 订阅事件。 Parent 发出事件。
经过以下一系列步骤后:
1. 隐藏 child
2. 显示 child
3.触发事件
事件被处理了n+1次。其中 n 是试验次数。
此示例的 Plunk:https://plnkr.co/edit/TWHO6PPYa55QGoHDXdFN
Parent 组件模板:
<div *ngIf="show">
<my-child-app></my-child-app>
</div>
Parent相关class代码:
show:boolean = true;
constructor(private service: AppService) {
}
changeShow(){
this.show = !this.show;
}
emitSome(){
this.service.appEvent.emit("abc");
}
Child 相关代码部分:
constructor(private service: AppService) {
this.service.appEvent.subscribe((s: string) => console.log(s));
}
您需要在销毁组件时清理订阅。每次由于 ngIf
显示子项时,它都会调用重新订阅发射器的子项的构造函数。修改您的代码以匹配以下内容:
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();
}
}
在我的应用程序中,我注意到了意外行为。可能我犯了一个错误,但我不知道在哪里。
场景:我有两个组件:parent 和 child。 Parent模板包含'*ngIf'条件,是否显示child。 Parent 和 child 共享服务。 Child 订阅事件。 Parent 发出事件。
经过以下一系列步骤后: 1. 隐藏 child 2. 显示 child 3.触发事件
事件被处理了n+1次。其中 n 是试验次数。 此示例的 Plunk:https://plnkr.co/edit/TWHO6PPYa55QGoHDXdFN
Parent 组件模板:
<div *ngIf="show">
<my-child-app></my-child-app>
</div>
Parent相关class代码:
show:boolean = true;
constructor(private service: AppService) {
}
changeShow(){
this.show = !this.show;
}
emitSome(){
this.service.appEvent.emit("abc");
}
Child 相关代码部分:
constructor(private service: AppService) {
this.service.appEvent.subscribe((s: string) => console.log(s));
}
您需要在销毁组件时清理订阅。每次由于 ngIf
显示子项时,它都会调用重新订阅发射器的子项的构造函数。修改您的代码以匹配以下内容:
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();
}
}