ng-event-bus

Real-Time Notifications in Angular with ng-event-bus

Ever built an Angular app where components needed to communicate without being directly connected? Maybe you wanted a global notification system that updates instantly, no matter where the user is in your app?

That’s where `ng-event-bus` shines. It acts as a lightweight event bus, letting different parts of your application talk to each other seamlessly.

In this article, we’ll build a real-time notification system using `ng-event-bus`—no messy service injections, no complex state management.

Why Use ng-event-bus?

Let’s face it: passing data between unrelated components in Angular can be a headache. Services with `Subject` and `BehaviorSubject` from RxJS work, but they require dependency injection, which isn’t always convenient.

`ng-event-bus` provides a simple, global event system that makes component communication effortless. It’s great for:

✅ Notifications (like we’ll build today!).

✅ Inter-component communication without tightly coupling them.

✅ Broadcasting events globally without injecting services everywhere.

✅ Handling WebSocket events, where multiple components react to real-time data.

Setting Up `ng-event-bus`


First, install `ng-event-bus` in your Angular project:

npm install ng-event-bus

Then, provide it in your app configuration. Since Angular now supports standalone APIs, let’s add it to `app.config.ts`:

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';  
import { provideRouter } from '@angular/router';  
  
import { routes } from './app.routes';  
import { NgEventBus } from 'ng-event-bus';  
  
export const appConfig: ApplicationConfig = {  
  providers: [  
    provideZoneChangeDetection({ eventCoalescing: true }),  
    provideRouter(routes),  
    NgEventBus  
  ]  
};

Boom! 🎉 Your app now has a global event bus.

Creating a Notification Service

Let’s create a `NotificationService` to manage notifications:

import { Injectable, inject } from '@angular/core';  
import { NgEventBus } from 'ng-event-bus';  
  
@Injectable({ providedIn: 'root' })  
export class NotificationService {  
  private readonly eventBus = inject(NgEventBus);  
  
  sendNotification(message: string) {  
    const notification = { message, timestamp: new Date() };  
    this.eventBus.cast('notification', notification);  
  }  
}

This service will broadcast notifications to all listeners using `eventBus.cast()`.

Sending a Notification

Now, let’s create a component that triggers a notification:

import { Component, inject } from '@angular/core';  
import { NotificationService } from '../services/notification.service';  
  
@Component({  
  selector: 'app-socials',  
  template: `<button (click)="sendNotification()">Send Notification</button>`  
})  
export class SocialsComponent {  
  private readonly notificationService = inject(NotificationService);  
  
  sendNotification() {  
    this.notificationService.sendNotification('New message received!');  
  }  
}

This component calls `sendNotification()` when the button is clicked.

Listening for Notifications

Next, we need a component that listens for notifications:

import { Component, OnInit, inject } from '@angular/core';  
import { NgEventBus } from 'ng-event-bus';  
  
@Component({  
  selector: 'app-notification-list',  
  template: `@for (notification of notifications; track notification.id) {  
  <div>  
    {{ notification.message }} ({{ notification.timestamp | date:'shortTime' }})  
  </div>  
} @empty {  
  <p> No notification yet.</p>  
}`  
})  
export class NotificationListComponent implements OnInit {  
  private readonly eventBus = inject(NgEventBus);  
  notifications: { message: string; timestamp: Date }[] = [];  
  
  ngOnInit() {  
    this.eventBus.on('notification').subscribe((event) => {  
      this.notifications.push(event.data);  
    });  
  }  
}


This component listens for `notification` events and updates the notification list dynamically.

Conclusion

With `ng-event-bus`, we've built a lightweight real-time notification system in Angular. This approach is great for global events like notifications, user status updates, or WebSocket messages. By decoupling components, we keep our architecture clean and scalable.

Comments

Popular posts from this blog

RxJS Operátorok

Bevezetés az NgRx-be