lolol
lolol

Reputation: 4390

Get event name in Nestjs and EventEmitter2 handler

I have the following code:

  @OnEvent("**")
  public handleEverything(parentId: number): void {
    // @ts-expect-error this.envent
    console.log(this.event)
  }

I tried to get the event name by using the this.event but it returns undefined. Is there a way to get the event name inside the handler using Nestjs and EventEmitter?

Upvotes: 1

Views: 1450

Answers (2)

Sergey Mell
Sergey Mell

Reputation: 8040

You can use onAny method of the event emitter. So your code may look as follows

this.eventEmitter
  .onAny((event: string | string[], ...values: any[]) => {
    // Handler code here
  });

So in this case you can handle both - event name and broadcasted message.

Upvotes: 0

Kien Nguyen
Kien Nguyen

Reputation: 2691

I think that is not possible. You can instead add a parameter to the payload when dispatching event and use it in the handler:

Dispatching:

this.eventEmitter.emit('eventName', { type: 'eventType', others: 'others' });

Listening:

@OnEvent("**")
public handleEverything(payload: any): void {
  if (payload.type === 'eventType') {
    // do something
  }
}

Upvotes: 2

Related Questions