2017-04-10 30 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(); 
    } 
}