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 个日志而不是 1 个,因为 emitLog 只发出一次。
解决方案
两个实现者都继承了 ngOnInit,因此假设它们都被渲染,预计 emitLog 会被调用两次。
换句话说,您发出日志的触发器是 on-init 生命周期钩子。
如果您希望它被调用一次,您所要做的就是找到满足您要求的适当触发器,例如单击任何组件。
推荐阅读
- windows-installer - 如何在 Installshield 2018 中添加发布者
- javascript - 在此 Javascript 中更改 div 和 span 的顺序
- c# - 使用 LowLevelMouseProc 捕获触摸事件不适用于所有应用程序
- mysql - MySql:使用 WHERE 子句将数据从一个表复制到另一个表
- android - 执行 SU 命令
- r - 仅基于另一列中的一个条件归还特定类型的所有行
- java - 如何在折线图中留出空白?
- java - Java 应用程序中 io.vertx.core.impl.EventLoopContext 中的内存泄漏
- node.js - firebase nodeJs 收到电子邮件解析问题
- java - 当我尝试将 angularJs 应用程序连接到 Spring Boot 时出现 401