Simple Angular event bus to pass data between views

You might have in your application unrelated components that interact (or should) with each other.

For example, a navigation bar, shown all along the different views is created inside application parent component and may display data that should change when other view is updated.

With Angular 1.x $broadcast and $emit services were  doing the job by broadcasting messages to potential subscribers.

With Angular 2+, to keep a low dependency relation between components and still be able to notify components of a change they could be affected by, Message Bus pattern is a good solution.

It can be implemented in various ways, from the simplest to the most complex. Here, we’ll try to keep it as simple as possible :

  • Strong typing
  • Message filtering based on message type
  • Low coupling between components

Implementation

Message bus will consist in a simple class with only a dependency on Rxjs library.

 

Just add EventsService to @NgModule.providers in your module class and inject it in components that will use it.

It’s ready !

Sources :

Message Bus pattern

Leave a Reply

Your email address will not be published. Required fields are marked *