Angular 11.x implementation of the publish subscribe Pattern.
If you enjoy @fsms/angular-pubsub, please consider pressing the star button on my repo & supporting me for years of development (and to unlock rewards!) β€
Table of Contents
npm installation
npm i -S @fsms/angular-pubsub
You need Message
class to create your messages and you need PubsubService
to publish or subscribe messages.
Message
holds messageType
and optional payload
export interface IMessage {
messageType: string;
payload?: any;
}
Example of one message:
import { DefineMessage, IMessageSchema, IMessage } from '@fsms/angular-pubsub';
@DefineMessage<IMessageSchema>()
export class PlaceOrder implements IMessage {
static messageType = '[Sells] Place Order';
messageType = PlaceOrder.messageType;
constructor(public payload?: string) {}
}
pubsubService
is used to publish and subscribe messages.
publish<V extends IMessage = IMessage>(message: V): void;
subscribe({
messageType,
callback,
error,
complete,
}: SubscribeOptions): PubsubSubscription;
Initialize module for root in your angular root module
import { PubSubModule } from '@fsms/angular-pubsub'; π // Importing Angular Pubsub module
@NgModule({
declarations: [
RootComponent,
NavigationComponent,
OverlayComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
PubSubModule.forRoot() π // Initiate Pubsub module
],
providers: [],
bootstrap: [RootComponent]
});
PubsubService
as dependency in component Go to desired component and subscribe to a message.
import { Component } from '@angular/core';
import { PubsubService } from '@fsms/angular-pubsub';π // Importing Angular Pubsub module
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(
private pubsubService: PubsubService/* <= HERE */) {}
π// Injecting Angular Pubsub Service
}
Subscribing to message
In ngOnInit
method of angular, you can subscribe to the events that you want to react upon.
import { PubsubService, PubsubSubscription } from '@fsms/angular-pubsub';
import { PlaceOrder } from './orders/messages/place-order-message';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
subscriptions: PubsubSubscription[] = [];
constructor(private pubsubService: PubsubService) {}
ngOnInit(): void {
this.subscriptions.push(
this.pubsubService.subscribe({ π// Subscribing to a message
messageType: PlaceOrder.messageType,
callback: (msg) => console.log('received', msg),
})
);
}
}
publish
method takes one argument where it expect the Message
object.Example: Now on a button click, I want to publish a message with some payload.
import { Component } from '@angular/core';
import { OrderPlaced } from './messages/placeorder-message';
import { PubsubService } from '@fsms/angular-pubsub';// <= HERE
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(
private pubsubService: PubsubService/* <= HERE */) {}
orderPlaced($event: KeyboardEvent) {
$event.preventDefault();
this.pubsubService.publish( π// Publishing a message
new OrderCreated({
orderId: new Date().getTime().toString(36),
item: '20 Apples',
})
);
}
}
Keep all subscriptions per component in an array. And On component you must unsubscribe your subscriptions on ngOnDestroy
event.
ngOnDestroy(): void {
this.subscriptions.forEach((s) => s.unsubscribe());π// Unsubscribing a message
}
Convert Angular service to a Message Handler. If to organize your angular code base as Service Oriented Architecture (SOA) way. And you want to create an Angular service that can listen to a Message and react on them just like a N-ServiceBus Message Handlers?
Then you must use @RegisterHandler({})
decorator on any Angular Service then it will automatically be registered as message subscriber. This helps us to organize your business logic in services rather in angular components.
Message Handler
Message handler is a service that can listen to one message or more messages and perform business logic. Message Handler can also publish after handling incoming messages.
Diagram of a Angular Service as Message Handler called as ShipOrderService
which listens to OrderReady
message and process shipping then publishes OrderShipped
message.
Creating Message Handler at Root Module
Example: When Order is Ready Shipping service is starting the shipment process.
import { Injectable } from '@angular/core';
import {
CallbackOptions,
IHandleMessage,
RegisterHandler,
} from '@fsms/angular-pubsub';
import { OrderReady } from '../messages/order-ready-message';
import { OrderShipped } from '../messages/order-shipped-message';
@Injectable({ providedIn: 'root' }) // Angular Service
@RegisterHandler({ π
messages: [OrderReady],π // You can listen to many messages
})
export class ShipOrderService implements IHandleMessage<OrderReady> {
handle({ message, context }: CallbackOptions<OrderReady>): void {
console.log('[Shipping] Order Shipped', message);
context.publish(new OrderShipped(message.payload));
π // context will have publish method to publish any message from message handler.
}
}
Use PubsubModule.forRoot([])
to register your app message handlers.
Example: Registering ShipOrderService
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { PubsubModule } from '@fsms/angular-pubsub';
import { AppComponent } from './app.component';
import { ShipOrderService } from './services/ship-order.service';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
FormsModule,
PubsubModule.forRoot([ // Register App Module level Message Handlers
ShipOrderService, π
]),
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
Creating Message Handler at Feature Module Level
In order to achieve true service oriented architecture. You must create independent isolated feature modules. The message handlers gives you the power to register your message handlers at feature module level.
Example: Create Order
Message handler in Orders
module.
import { CallbackOptions, IHandleMessage } from '@fsms/angular-pubsub';
import { RegisterHandler } from 'projects/fsms-angular-pubsub/src/lib/pubsub-decorator';
import { OrderCreated } from 'src/app/messages/order-created-message';
import { PlaceOrder } from '../messages/place-order-message';
@RegisterHandler({π // Create as Message Handler
messages: [PlaceOrder],
})
export class CreateOrderService implements IHandleMessage<PlaceOrder> {
constructor() {}
handle({ message, context }: CallbackOptions<PlaceOrder>): void {
console.log(`[Sales] Order Created`, message);
context.publish(
new OrderCreated({
orderId: new Date().getTime().toString(36),
item: message.payload,
})
);
}
}
Use PubsubModule.forFeature([])
to register your feature message handlers.
Example: Registering CreateOrderService
at orders module.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SubmitOrderComponent } from './submit-order/submit-order.component';
import { CreateOrderService } from './services/create-order.service';
import { PubsubModule } from '@fsms/angular-pubsub';
@NgModule({
declarations: [SubmitOrderComponent],
imports: [CommonModule,
PubsubModule.forFeature([CreateOrderService]) π // Registering as feature message handler
],
exports: [SubmitOrderComponent],
})
export class OrdersModule {}
Contributions are welcome!π If you find any problems or would like to contribute in any way, feel free to create a pull request/open an issue/send me a message.
You can also contribute by becoming an official sponsor to help keep Angular Pub-Sub well-maintained.
π Say π to me!
Rupesh Tiwari
www.rupeshtiwari.com
βοΈ Email Rupesh Tiwari
Founder of Fullstack Master