background

Messaging is one of the most commonly used components in development today. None of them. There are different ways of messaging, but anyway. What fits is best.

In a lot of systems. Message delivery is not complex enough to require various class libraries to handle. Increases the cost of starting a new student. There are only a few types of data that might need to be listened to and passed around, so the introduction of libraries like NGRX, NGXS, Redux, MOBx, vuex, etc., only adds additional complexity. So make a BUS directly with RXJS.

EventBus

EventBus is an event publish/subscribe framework that simplifies event delivery by decoupling publishers and subscribers. This is especially true when multiple layers of controllers are nested.

The best thing about EventBus is its simplicity and decoupling. Before EventBus, we used broadcast for listening, or custom interface function callbacks, such as $broadcast and $emit for NG1, $emit and $ON for VUE, etc.

Image from EventBus GitHub homepage

Cut the crap and get right to the code

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable(a)export class PubSubService {
pub = new Subject<Event>();
pub$ = this.pub.asObservable();
publish(event: Event) {
this.pub.next(event); }}export class Event {
type: EventType;
data: any;
}
export enum EventType {
type1,
type2
}
Copy the code

Complete.. If you don’t count definition classes and enumerations. There are five lines of code. There’s nothing wrong with the old iron.

Method of use


// Subscribe when the component is initialized
initOnCompanyChange() {
if (this.pubSubService.pub$.subscribe) {
this.subscription = this.pubSubService.pub$.pipe(
// You can see all the data going through this topic
tap(event= > {
console.log('Received data');
console.log(event.data);
}),
// We only need to care about the type of events and data we need
filter(event= > event.type === EventType.type1)
).subscribe(event= > {
// Once you get it, you can do whatever you want
console.log('receives TYPE1 data:');
console.log(event.data); }); }}// Send events and data of type type1
testChangeType1() {
this.pubSubService.publish({
type: EventType.type1,
data: {
key: Here we go, here we go.,
value: 'ooooooo'}}); }// Send events and data of type Type2
testChangeType2() {
this.pubSubService.publish({
type: EventType.type2,
data: {
key: 'Here we go, here we go.',
value: 'NNNNNN'}}); }// Unsubscribe when the component is destroyed to avoid memory leaks
ngOnDestroy(): void {
this.subscription.unsubscribe();
}

Copy the code

If you need a BehaviorSubject, change the Subject to BehaviorSubject. For details, see the sample code github, BehaviorSubject, ReplaySubject, AsyncSubject