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

不羁的心 提交于 2019-12-10 14:13:00

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/32711093/how-do-i-create-a-publisher-subscriber-model-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!