DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for The Angular Event Service
John Peters
John Peters

Posted on • Updated on

The Angular Event Service

An Event Service is a service that only contains events. It is imported into any loaded component wanting to subscribe to or emit content. It allows cross component communication for any and all loaded components.

The image above shows how a component subscribes to an event in the event service. Any other component which emits to that event is now communicating to all listeners.

Create A New Service

Step 1) Create a new service in the proper folder using this syntax.

generate service

Step 2) Define your events in the service class just created:

define events

The EventEmitter

The generic form of the EventEmitter is found in the Angular/core module.

EventEmitters can send data (or no data) as shown in the examples above. In the "NewProcessPostResponseEvent" we define a type of data all listeners should expect as well as all emitters have to follow. This allows us to see what type to expect on the Subscribe side, very nice for taking guess work out.

Step 3) Subscribe to the event. Note you must import your event service!

subscribe

The EventService is imported to alls components wanting to communicate, either to emit or (listen) for data updates. (see the private declaration in the constructor?) The best part is the service automatically loads at load-time making all components able to communicate.

Decorators?
Sure... just put this into the event service.

decorator

Call it like this:

notify

JWP2019

Top comments (2)

Collapse
 
emiliojva profile image
EmΓ­lio Vieira

Nice!

Collapse
 
deivisons profile image
deivisons

Nice tutorial, simple and effient

DEV

Thank you.

Β 
Thanks for visiting DEV, we’ve worked really hard to cultivate this great community and would love to have you join us. If you’d like to create an account, you can sign up here.