loading...
Cover image for The Angular Event Service

The Angular Event Service

jwp profile image John Peters Updated on ・2 min read

Angular Tips (8 Part Series)

1) Angular to Typescript to Javascript models 2) The Angular Event Service 3 ... 6 3) MaterialExpander : Open from code 4) Angular State Management Options 5) Angular Events vs. Observables 6) Angular CSS using Directives only 7) Angular Form Validation Patterns 8) Angular Documentation (Fast)

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

Angular Tips (8 Part Series)

1) Angular to Typescript to Javascript models 2) The Angular Event Service 3 ... 6 3) MaterialExpander : Open from code 4) Angular State Management Options 5) Angular Events vs. Observables 6) Angular CSS using Directives only 7) Angular Form Validation Patterns 8) Angular Documentation (Fast)

Posted on by:

jwp profile

John Peters

@jwp

Angular, React, Typescript and JavaScript. The wave of now! Ok Vue too!

Discussion

markdown guide