9

I've been playing with Angular and have been trying to find a way to use a pub/sub mechanism across the whole component tree.

It seems that EventEmitter is only emitting an event that can be subscribed to one level up - but not more. Similarly, it only emits the events up the tree but now down.

plunker

The relevant code is here:

class App {
  onAncestor($event) {
     console.log('in ancestor, decendent  clicked',$event);
  } 
}

 ...
class Entities {
   ....
   onParent($event) {
     console.log('in entities parent, child  clicked',$event);
   } 

   onGrandParent($event) {
      console.log('in grand parent, grandschild  clicked',$event);
   } 

}

Only onParent is called, never onGrandparent or onAncestor. Similarly it wont publish downwards either.

Graham
  • 7,431
  • 18
  • 59
  • 84
Lior
  • 40,466
  • 12
  • 38
  • 40
  • Here is an example of how to use Observables/EventEmitter for pub sub http://www.syntaxsuccess.com/viewarticle/pub-sub-in-angular-2.0 – TGH Jan 02 '16 at 20:45

4 Answers4

6

With Angular 2 comes an observables library called RxJs, so that can be used to create a service that we can subscribe to and submit events.

Then we use the dependency injection mechanism to inject that service anywhere on the application where we need it.

So there is no need anymore for the broadcast/emit event mechanism as it was replaced by the more powerful observables mechanism, which is built-in everywhere in the framework: EventEmitter is an observable, form values are observables, http can return observables etc.

See this repository for examples of how to build services using RxJs for publish/subscribe.

Angular University
  • 42,341
  • 15
  • 74
  • 81
0

In the AngularJS 1.x world, you can use ng-contexts, a lightweight plug-in we wrote at my organization to enable fast and lazy state management for an application using a pub/sub model.

Intuitive state management for AngularJS applications

If you've moved on from AngularJS, obviously go with AngularUniversity's answer.

Tony Brasunas
  • 4,012
  • 3
  • 39
  • 51
0

https://www.npmjs.com/package/@fsms/angular-pubsub

this.pubsubService.subscribe({ // Subscribing to a message
        messageType: PlaceOrder.messageType,
        callback: (msg) => console.log('received', msg),
      })
this.pubsubService.publish( // Publishing a message
      new OrderCreated({
        orderId: new Date().getTime().toString(36),
        item: '20 Apples',
      })
    );
0

look at this lib ng-event-bus (https://www.npmjs.com/package/ng-event-bus)

It is RxJS-based message/event bus service for Angular apps inspired by NgRadio.

You have ability to publish msg, and in other part of the code subscribe to it.