首页 文章

角度组合ngIf和EventEmitter创建多个调用

提问于
浏览
1

在我的应用程序中,我注意到了意外可能我犯了一个错误,但我不知道在哪里 .

场景:我有两个组件:父母和孩子 . 父模板包含'* ngIf'条件,可以显示或不显示子项 . 父母和子女共享服务 . 孩子订阅活动 . 父发出事件 .

经过以下一系列步骤:1 . 隐藏孩子2.显示孩子3.触发事件

事件处理n次1次 . 其中n是试验次数 . Plunk这个例子:https://plnkr.co/edit/TWHO6PPYa55QGoHDXdFN

父组件模板:

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

家长相关 class 代码:

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

1 回答

  • 3

    您需要在销毁组件时清理订阅 . 每次因为 ngIf 而显示孩子时,它都会调用重新订阅 Launcher 的孩子的构造函数 . 修改您的代码以匹配以下内容:

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

相关问题