简体   繁体   English

Angular 7:如何发送和接收全球事件?

[英]Angular 7: How to send and receive a global event?

I study angular, sorry for the stupid question. 我研究角度,抱歉这个愚蠢的问题。

I need to make a service for windows with a single instance of the service or be able to send broadcast events and listen to them in each component. 我需要使用单个服务实例为Windows提供服务,或者能够发送广播事件并在每个组件中监听它们。

Using @input and @output is not like There is a different nesting of components. 使用@input和@output并不像是有不同的组件嵌套。

How to solve this issue? 如何解决这个问题?

One way to implement this is to use a service for that. 实现此目的的一种方法是使用服务。 Inside the service create an Subject member variable (you need RxJS for it, which angular already installed because it's a dependency). 在服务内部创建一个Subject成员变量(你需要RxJS,已经安装了angular,因为它是一个依赖项)。

The Subject can be subscribed by any component outside the service (you'll need to inject the service in the component constructor). Subject可以由服务外的任何组件订阅(您需要在组件构造函数中注入服务)。 Then, whenever you want to trigger that event you call .next() on the Subject and each subscriber will activate its own callback. 然后,只要您想触发该事件,就可以在Subject上调用.next(),每个订阅者都将激活自己的回调。

When subscription is done and not needed anymore it's important to .unsubscribe() from the Subject, otherwise there's a risk of memory leak (since the subscriber does not unsubscribe itself). 当订阅完成且不再需要时,重要的是来自Subject的.unsubscribe(),否则存在内存泄漏的风险(因为订阅者不会取消订阅)。

There are many examples out there, here is simple one. 有很多例子, 这里很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM