在Angular2发布/订阅模型(或:Angular2广播和散发) [英] Publisher/subscriber model in Angular2 (or: Angular2 to broadcast and emit)

查看:5545
本文介绍了在Angular2发布/订阅模型(或:Angular2广播和散发)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩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在这里:
     http://plnkr.co/edit/gputAG?p=info

plunker here: http://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广播和散发)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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