简体   繁体   中英

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.

Using @input and @output is not like There is a different nesting of components.

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).

The Subject can be subscribed by any component outside the service (you'll need to inject the service in the component constructor). Then, whenever you want to trigger that event you call .next() on the Subject and each subscriber will activate its own callback.

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).

There are many examples out there, here is simple one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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