In the previous post I covered the implementation of a simple event aggregator purely to demonstrate the key concepts of cross module communication as highlighted in the very first post. We concluded that the simple event aggregator is not DRY enough hence this post. In this final implementation again will utilise Rx to provide publish and subscribe functionalities, but also will utilise TypeScript Generics to achieve code reusability. Generics help you create objects of a class template that takes different types that are defined at run time by the client.

The following generic class encapsulates the code subscribing and publishing per event type.

Event Type

In order to tell the event aggregator on which event to react we have to define our own event that extends PubSubEvent<T>. This enables us to define our payload data object. You can define more events to fit your application following the same pattern.



All Together

Demo app source code.



One thought on “Angular 2 Cross Modules Communication: EventAggregator”

  1. Did you test the Generic Aggregator? The simple aggregator work fine on unsubscribe, however when unsubscribing using the DRY the statment “let foundIndex = this.subscriptions.findIndex(item => item[0] === observer);” always returns a -1. Do you have any thoughts on this?

Comments are closed.