Angular 角度组合ngIf和EventEmitter创建多个调用
在我的应用程序中,我注意到了意想不到的行为。也许我弄错了,但我不知道在哪里 场景:我有两个组件:父组件和子组件。 父模板包含“*ngIf”条件,可以显示也可以不显示子模板。 家长和孩子共享服务。子订阅事件。父项发出事件 完成以下一系列步骤后: 1.隐藏孩子 2.秀给孩子看 3.触发事件 事件被处理n+1次。其中n是试验次数。 对于此示例,请执行以下操作: 父组件模板:Angular 角度组合ngIf和EventEmitter创建多个调用,angular,eventemitter,Angular,Eventemitter,在我的应用程序中,我注意到了意想不到的行为。也许我弄错了,但我不知道在哪里 场景:我有两个组件:父组件和子组件。 父模板包含“*ngIf”条件,可以显示也可以不显示子模板。 家长和孩子共享服务。子订阅事件。父项发出事件 完成以下一系列步骤后: 1.隐藏孩子 2.秀给孩子看 3.触发事件 事件被处理n+1次。其中n是试验次数。 对于此示例,请执行以下操作: 父组件模板: <div *ngIf="show"> <my-child-app></my-child-app
<div *ngIf="show">
<my-child-app></my-child-app>
</div>
与儿童有关的守则部分:
constructor(private service: AppService) {
this.service.appEvent.subscribe((s: string) => console.log(s));
}
当组件被销毁时,您需要清理订阅。每次由于
ngIf
而显示子对象时,它都会调用子对象的构造函数,该构造函数会重新订阅发射器。修改代码以匹配以下内容:
导出类ChildComponent实现OnDestroy{
私人认购;
构造函数(专用服务:AppService){
this.eventSubscription=this.service.appEvent
.subscribe((s:string)=>console.log);
}
恩贡德斯特罗(){
此.eventSubscription.unsubscripte();
}
}
constructor(private service: AppService) {
this.service.appEvent.subscribe((s: string) => console.log(s));
}