抽象类中的Angular事件处理



我有从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 log而不是1,因为emitLog只发出一次。

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

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

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

最新更新