2

My goal is:

  • Allow all the messages of the app to be managed in a single component.

So far I came up with is:

  • MessageService: Singleton. Whoever wants to send a message calls addMsg here.

Messages are Subject observables.

newMessages: Subject<IMessage> = new Subject<IMessage>();

  • MessageViewer: A component that listens to MessageService and display the messages.

constructor(private _msgService: MessageService) { this._msgService.getMessages().subscribe( data => this.showMsg(data) ) }

Full demo here. https://plnkr.co/edit/aCXMtmiQhRL63EfT5lIy

Is that a good implementation or there is a better way to achieve this?

Daniel Pliscki
  • 1,913
  • 16
  • 24
  • 1
    Looks fine ;-) The remaining part is where you register this service. If it's for the whole application, it's when bootstrapping or in the main component... – Thierry Templier Jun 06 '16 at 18:41
  • 1
    See also http://stackoverflow.com/search?q=%5Bangular2%5D+event+bus and in particular http://stackoverflow.com/a/36782616/215945 – Mark Rajcok Jun 06 '16 at 19:03
  • 1
    Personally, I probably prefer using Observables as apposed to a Message Bus. This is how I realized the power of Event-Driven Architectures and Mediation a long time ago with KnockoutJS. I think Observables are more performant and easier to implement into a State-Machine; all you have to do on a Mediator is provide `.publish` & `.subscribe` methods that implement their own Message Filtering -- *which you want for Message Bussing anyway*; takes out some of the headache & boilerplate, though. **I'd give you a thumbs up for being one of the few to even go for this :)**. – Cody Jan 10 '17 at 20:30

0 Answers0