2017-04-10 92 views
1

在我的应用程序中,我注意到意外的行为。可能我犯了一个错误,但我不知道在哪里。Angular combine ngIf和EventEmitter创建多个调用

场景:我有两个组件:父和子。 父模板包含'* ngIf'条件并且可以显示或不显示子项。 家长和孩子分享服务。孩子订阅活动。家长发出事件。

系列下面的步骤后: 1.隐藏的孩子 2.秀子 3.触发事件

事件处理N + 1次。其中n是试验次数。 普拉克这个例子:https://plnkr.co/edit/TWHO6PPYa55QGoHDXdFN

父组件模板:

<div *ngIf="show"> 
    <my-child-app></my-child-app> 
</div> 

父相关类代码:代码

show:boolean = true; 
    constructor(private service: AppService) { 
    } 

    changeShow(){ 
    this.show = !this.show; 
    } 

    emitSome(){ 
    this.service.appEvent.emit("abc"); 
    } 

儿童相关部分:

constructor(private service: AppService) { 
    this.service.appEvent.subscribe((s: string) => console.log(s)); 
    } 

回答

3

您需要在组件销毁时清理订阅。每次由于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(); 
    } 
}