我一直在玩Angular2,并试图找到一种方法,使用发布/订阅机制,在整个组件树。
I've been playing with Angular2 and tried to find a way to use 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 downwards.
plunker在这里: plnkr.co/edit/gputAG?p=info
plunker here: plnkr.co/edit/gputAG?p=info
见
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
同样,它不会向下发布
我不知道该怎么做。
感谢您的想法利奥尔
thanks for any idea Lior
推荐答案通过角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.
所以没有必要再对所述广播/发射事件机制,因为它是由更强大的观测机制,这是内置的无处不在的框架所取代: EventEmitter 是一个可观的,形式的值是观测, 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.
请参阅此库对于如何使用RxJs用于发布构建服务实例/订阅。
See this repository for examples of how to build services using RxJs for publish/subscribe.
更多推荐
在Angular2发布/订阅模型(或:Angular2广播和散发)
发布评论