Event Emitter package (
@nestjs/event-emitter) provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other.
EventEmitterModule internally uses the eventemitter2 package.
First install the required package:
Once the installation is complete, import the
EventEmitterModule into the root
AppModule and run the
forRoot() static method as shown below:
.forRoot() call initializes the event emitter and registers any declarative event listeners that exist within your app. Registration occurs when the
onApplicationBootstrap lifecycle hook occurs, ensuring that all modules have loaded and declared any scheduled jobs.
To configure the underlying
EventEmitter instance, pass the configuration object to the
.forRoot() method, as follows:
To dispatch (i.e., fire) an event, first inject
EventEmitter2 using standard constructor injection:
info Hint Import the
Then use it in a class as follows:
To declare an event listener, decorate a method with the
@OnEvent() decorator preceding the method definition containing the code to be executed, as follows:
warning Warning Event subscribers cannot be request-scoped.
The first argument can be a
symbol for a simple event emitter and a
string | symbol | Array<string | symbol> in a case of a wildcard emitter. The second argument (optional) is a listener options object (read more).
To use namespaces/wildcards, pass the
wildcard option into the
EventEmitterModule#forRoot() method. When namespaces/wildcards are enabled, events can either be strings (
foo.bar) separated by a delimiter or arrays (
['foo', 'bar']). The delimiter is also configurable as a configuration property (
delimiter). With namespaces feature enabled, you can subscribe to events using a wildcard:
Note that such a wildcard only applies to one block. The argument
order.* will match, for example, the events
order.shipped but not
order.delayed.out_of_stock. In order to listen to such events,
multilevel wildcard pattern (i.e,
**), described in the
With this pattern, you can, for example, create an event listener that catches all events.
EventEmitter2class provides several useful methods for interacting with events, like
onAny. You can read more about them here.
A working example is available here.