繁体   English   中英

Angular 抽象事件处理 class

[英]Angular event handling in abstract class

我有从 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 只发出一次。

两个实现者都继承了 ngOnInit,因此假设它们都被渲染,那么 emitLog 应该被调用两次。

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

如果你想让它被调用一次,你所要做的就是找到满足你要求的合适的触发器,例如点击任何一个组件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM