I’m going to introduce
something called an event bus. An event bus is passing data between different
components, and it's going to be a type of mediator or middleman. One component
wants to talk to another component out there that it may not even know about,
it can send data through the event bus, and then the other component can obtain that data. the event bus is going to be the communication mechanism between the
components. Here we are using Mediator pattern and RxJS Subject.
When selecting a user
UserListComponent raises a 'UserSelect' event and passes data to the Event
bus service. After that happen event bus service doesn't know who's
listening at all. then, UserDetailsComponent will get the event data and
be able to show the user details on the component.
Let's
focus on code level implementation now.
The
key to EventBusService is the 'Subject'. And we can see there is a private RxJS
subject. Now, this particular subject could send any type of data, because that
is in 'any' type. But if you only need specific types of data, you could certainly
lock that down with a class type or an interface or maybe it's just a number or
something like that.
When
selecting a new user UserListComponent calls the 'emit' of the event bus
service and passing event type and data to the 'emit'.
Here
UserDetailsComponent subscribes EventBusService 'on' and that returns
newly created user data back to the UserDetailsComponent.
You can use this
EventBusService to pass any type of data within components in your angular application.
This approach is very simple to use. You can call 'emit' anytime you want to send
an event, or you call 'on' anytime you want to subscribe to an event. It is very
loosely coupled, very lightweight and very little code.
Github Project >>>
Comments
Post a Comment