Angular application should be built by assembling small and atomic level components which follows SOLID principles. One of the challenge occurs when components needs to pass data and message between each other. If components are in Parent-Child hierarchy then it is very easy to implement using @Input() and @Output() decorators. But when components are not related with each other, then it becomes bit tricky. One of the solution is creating a Dependency Injectable service class which will aggregate events and pass between components. Since it is repetitive process, I have published a npmjs package ng-event-brokerwhich expose EventBrokerService. In this story we will see how to use it.
Define your application level events in separate file
. Before publishing or subscribing to any events, they must be registered. As AppComponent is root component, we should define our application wide events here.
Once events are registered, we can publish and subscribe them in rest of application. For example, in below code HeaderComponent subscribe to event
To publish event, simply callpublishEvent(payload)wherepaylaodcan be value of typeany. Make sure, event is registered first using `registerEvent()` before publishing.
To subscribe event, simply call `subscribeEvent()` function which returns `EventEmitterany`. You can call `subscribe()` on this event emitter and handle event.
We can clear all events using `clearEvents()` function.
You can find complete source code of very basic eShop demo application and see how events are passed and handled throughout the application.
In Angular application, we often require to pass data and messages between components and classes. If parent/child
Full Stack Developer, GitHub Developer Program Member, Angular enthusiast!
Welcome to a place where words matter. OnWatch
Follow all the topics you care about, and well deliver the best stories for you to your homepage and inbox.Explore
Get unlimited access to the best stories onUpgrade