简体   繁体   English

Angular 抽象事件处理 class

[英]Angular event handling in abstract class

I have Component1 and Component2 which are extended from AbstractComponent.我有从 AbstractComponent 扩展而来的 Component1 和 Component2。 I need to listen for an event in AbstractComponent.我需要在 AbstractComponent 中监听一个事件。 However, when a event is emitted, handle method on AbstractComponent is called twice.但是,当发出事件时,会调用 AbstractComponent 上的 handle 方法两次。 I think it is because it has two implementers which are Component1 and Component2.我认为这是因为它有两个实现者,即 Component1 和 Component2。

How can I prevent handling twice for the same event in AbstractComponent?如何防止在 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)
      }
  }
}

So I see 2 log instead of 1 since emitLog is emitted only once.所以我看到 2 个日志而不是 1 个日志,因为 emitLog 只发出一次。

Both implementers inherit ngOnInit, so assuming they are both being rendered it is expected that emitLog is called twice.两个实现者都继承了 ngOnInit,因此假设它们都被渲染,那么 emitLog 应该被调用两次。

In other words, your trigger for emitting log is the on-init lifecycle hook.换句话说,您发出日志的触发器是 on-init 生命周期挂钩。

If you want it to be called once, all you have to do is to find the appropriate trigger that meets your requirements, eg clicking any of the components.如果你想让它被调用一次,你所要做的就是找到满足你要求的合适的触发器,例如点击任何一个组件。

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

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