DEV Community

Cover image for The Angular Event Service
JWP
JWP

Posted on • Edited on

9

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

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!