Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a publisher/subscriber model in Angular?

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.

like image 376
Lior Avatar asked Sep 22 '15 07:09

Lior


People also ask

What is Pubsub in angular?

In software architecture Pub/Sub is publish-subscribe that is a messaging pattern. Message is a Plain JavaScript Object with type and optional payload. Where senders of the messages, called publishers. Receiver of the messages are called subscribers.

Why We Use subscribe in angular?

Normally Subscription means an arrangement to receive something. Similarly, in Angular applications Observables will be connected to observers and whenever they observe a new value or change in data, they will execute code with the help of Subscription and all the subscribed components will receive the updated outcome.

How does a pub/sub model work?

In a pub/sub model, any message published to a topic is immediately received by all of the subscribers to the topic. Pub/sub messaging can be used to enable event-driven architectures, or to decouple applications in order to increase performance, reliability and scalability.


1 Answers

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.

like image 136
Angular University Avatar answered Oct 21 '22 16:10

Angular University