2017-04-10 1 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 때문에 아이가 표시 될 때마다 Emitter를 다시 구독하는 자식의 생성자를 호출합니다. 다음과 일치하도록 코드를 수정하십시오.

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(); 
    } 
}