在Angular2发布/订阅模型(或:Angular2广播和散发)

编程入门 行业动态 更新时间:2024-10-26 10:26:59
本文介绍了在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在这里:     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广播和散发)

本文发布于:2023-11-01 17:37:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549973.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!