如何在Angular中创建发布者/订阅者模型? [英] How do I create a publisher/subscriber model in Angular?

查看:189
本文介绍了如何在Angular中创建发布者/订阅者模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Angular,一直在尝试寻找一种在整个组件树中使用pub/sub机制的方法.

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.

似乎EventEmitter仅发出可以预订到更高级别的事件-但不能更多.同样,它仅将事件向上发射到树上,而现在向下发射.

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.

朋克车

相关代码在这里:

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);
   } 

}

仅调用onParent,而不调用onGrandparent或onAncestor.同样,它也不会向下发布.

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

推荐答案

Angular 2附带了一个名为RxJs的可观察性库,因此可用于创建我们可以订阅和提交事件的服务.

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.

因此,不再需要广播/发射事件机制,因为它已被功能更强大的Observables机制所取代,该机制内置在框架的各处:EventEmitter是可观察的,表单值是Observable,http可以返回观测值等.

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.

有关如何使用RxJ进行发布以构建服务的示例,请参见存储库/订阅.

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

这篇关于如何在Angular中创建发布者/订阅者模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆