首页 > 解决方案 > 抽象类中的角度事件处理

问题描述

我有从 AbstractComponent 扩展而来的 Component1 和 Component2。我需要在 AbstractComponent 中监听一个事件。然而,当一个事件被触发时,AbstractComponent 上的 handle 方法会被调用两次。我认为这是因为它有两个实现者,即 Component1 和 Component2。

如何防止在 AbstractComponent 中对同一事件进行两次处理?

@Component({
  selector: 'FirstLogComponent'
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FirstLogComponent extends AbstractLogComponent {

  public constructor(
    public logService: LogService,
  ) {
    super(logService);
  }

}


import { LogService } from "../../../../../../../core/services/log.service";


@Component({
  selector: 'SecondLogComponent'
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SecondLogComponent extends AbstractLogComponent {

  public constructor(
    public logService: LogService,
  ) {
    super(logService);
  }

}



import { OnInit } from '@angular/core';
import { ReactiveComponent } from '../../ReactiveComponenet';
import { take as rxTake } from 'rxjs/internal/operators';
import { takeUntil as rxTakeUntil } from 'rxjs/internal/operators';


export abstract class AbstractLogComponent extends ReactiveComponent implements OnInit {

  public constructor(public logService) {
    super();

  }

  public ngOnInit() {
    this.logService.emitLog.pipe(rxTakeUntil(this.destroyed$))
    .subscribe((log) => {
        console.log(log)
      }
  }
}

所以我看到 2 个日志而不是 1 个,因为 emitLog 只发出一次。

标签: angulartypescript

解决方案


两个实现者都继承了 ngOnInit,因此假设它们都被渲染,预计 emitLog 会被调用两次。

换句话说,您发出日志的触发器是 on-init 生命周期钩子。

如果您希望它被调用一次,您所要做的就是找到满足您要求的适当触发器,例如单击任何组件。


推荐阅读