1
头图

This article discusses how two Angular Components can communicate if they are unaware of each other's existence and have no shared parent-child Component.

In many front-end frameworks including Angular, there are always communication problems when we divide an application or page into many small UI components and bind events to a component that is nested many levels.

In Angular, we use @Output() and @Input(). This works fine under normal circumstances, but can be a nightmare to manage when we want to bind incoming data and outgoing events to a container component.

We need to add a lot of @Input() and @Output() on many levels of the component.

This article describes two solutions:

  • Event Bus by using Subject.
  • Observable Service with Behavior Subject.

The discussed scenario is that there is an Angular Component with many article lists, and clicking on an item can view the article details.

Event Bus Solution

We create a globally available event bus service.

We can then emit an event to the bus and if any listener is registered to that event name then it will execute the callback function.

In this article, I will create event bus service using RsJS subject.

From the list of articles, each time the user clicks on the item, it emits an event and passes the article data to the event bus.

The above code shows how to send the event SelectArticleDetail together with the selected article data through the event bus.

Next, we use the on method of the event bus service in the Article Detail Component to listen to the SelectArticleDetail event thrown by the latter.

The callback function we define here saves the Article data thrown by the event bus service into the Component property detail.

Observable Service Solution

The idea is simple, create an inventory to pass the value inside. So every time the stock changes, the observer will know about it and execute the callback.
We create a BehaviorSubject with the default article value named inventorySubject$ and the addToInventory() method to add articles to the inventory.

In the article list, each time the user clicks on an item, the Observable service addToInventory method is called, and the current article is passed into the this.inventorySubject$.next method.

Then in the article detail Component, we subscribe to changes in this.inventorySubject$:

When to use these two schemes?

We use Observable Service to subscribe data for simple case, we use Event Bus to dispatch different event names to different listeners.

More Jerry's original articles, all in: "Wang Zixi":


注销
1k 声望1.6k 粉丝

invalid