【问题标题】:Angular combine ngIf and EventEmitter creates multiple callsAngular 结合 ngIf 和 EventEmitter 创建多个调用
【发布时间】:2017-04-10 19:36:23
【问题描述】:

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

场景:我有两个组件:父母和孩子。 父模板包含 '*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));
  }

【问题讨论】:

    标签: angular eventemitter


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 2018-08-08
      • 2018-08-17
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2018-07-15
      相关资源
      最近更新 更多