README
NgxEventBus
An angular library for dispatching event to easily communicate between component-component, service-component, and many more.
Install
npm install @itsquarehub/ngx-event-bus
or
yarn add @itsquarehub/ngx-event-bus
Usage
Installation
import { EventBusModule } from '@itsquarehub/ngx-event-bus';
@NgModule({
imports: [
EventBusModule.forRoot(),
]
})
Creation of custom event. Inherit the EventBusState class
import { EventBusState } from '@itsquarehub/ngx-event-bus';
export class ShowLoaderEvent extends EventBusState<void> {
constructor() {
super('ShowLoaderEvent');
}
}
Register event listener
import { Subscription } from 'rxjs';
import { EventBusDispatcherService } from '@itsquarehub/ngx-event-bus';
export class EventClassSample {
private _showLoaderHandler: Subscription;
constructor(private _eventDispatcher: EventBusDispatcherService) {
this._showLoaderHandler = this._eventDispatcher.addEventListener(
new ShowLoaderEvent(), this._onShowLoader.bind(this)
);
}
public ngOnDestroy(): void {
if (this._showLoaderHandler) {
this._showLoaderHandler.unsubscribe();
this._showLoaderHandler = null;
}
}
private _onShowLoader(): void {
console.log('Show loader.');
}
}
Note don't forget to unsubscribe your handler, to prevent memory leak.
Dispatching an event
import { EventBusDispatcherService } from '@itsquarehub/ngx-event-bus';
export class EventClassSample {
constructor(private _eventDispatcher: EventBusDispatcherService) {
this._eventDispatcher.dispatch(new ShowLoaderEvent());
}
}