我有一个监听事件的监听器,但我也希望该监听器调用其他服务来执行事件中的操作。即创建数据库通知,发送短信等。
当我创建一个构造函数来注入依赖的服务时,侦听器停止拾取事件,当我使用服务删除构造函数时,它会再次开始工作。
我需要如何构造这个监听器才能调用其他服务,例如下面示例中的NotificationsService?
客户端更新.listener.ts
@Injectable()
export class ClientUpdatedListener {
constructor(
@Inject(NotificationsService) private notificationService) {
}
private readonly logger = new Logger(ClientUpdatedListener.name);
@OnEvent(eventType.CLIENT_UPDATED)
handleClientUpdatedEvent(event: ClientUpdatedEvent) {
this.logger.log('Processing event: ' + eventType.CLIENT_UPDATED );
console.log(event);
this.notificationService.emailClient(event.id);
}
Run Code Online (Sandbox Code Playgroud)
通知服务。目前它是一个 shell,但我希望在其中执行逻辑并可能执行数据库调用。
@Injectable()
export class NotificationsService {
constructor(
@Inject(TENANT_CONNECTION) private tenantDb,
) {}
emailClient(id: string) {
console.log(id);
}
}
Run Code Online (Sandbox Code Playgroud)
调用服务代码
const clientUpdatedEvent = new ClientUpdatedEvent();
clientUpdatedEvent.id = id;
this.eventEmitter.emit(eventType.CLIENT_UPDATED, clientUpdatedEvent);
Run Code Online (Sandbox Code Playgroud)
您会注意到文档中有一个明确的警告,指出事件侦听服务无法REQUEST确定作用域。如果您需要访问请求范围的服务,则需要将请求信息作为事件负载的一部分传递,并使用 ModuleRef和 ContextIdFactory生成当前子树的上下文 id,然后NotificationsService从那个子树。
| 归档时间: |
|
| 查看次数: |
4208 次 |
| 最近记录: |