Blog>
Snippets

Real-Time Notifications

Create a notification service in Angular that listens to a WebSocket connection to display alerts and messages to users instantly.
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';

@Injectable({
  providedIn: 'root'
})
export class NotificationService {
  private notification$: WebSocketSubject<any>;
  public notifications: Subject<any> = new Subject<any>();

  constructor() {
    this.notification$ = webSocket('ws://example.com/notifications'); // WebSocket connection URL
    this.notification$.subscribe(
      (message) => this.notifications.next(message),
      (err) => console.error(err),
      () => console.warn('Completed!')
    );
  }

  getNotificationObservable(): Observable<any> {
    return this.notifications.asObservable();
  }

  closeConnection(): void {
    this.notification$.complete();
  }
}
Injectable notification service that establishes a WebSocket connection and streams data using RxJS. Incoming messages are passed to a Subject which can then be observed by other components.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { NotificationService } from './notification.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-notification-component',
  template: `<div *ngIf="message" class="notification">{{ message }}</div>`
})
export class NotificationComponent implements OnInit, OnDestroy {
  message: string;
  private notificationsSubscription: Subscription;

  constructor(private notificationService: NotificationService) {}

  ngOnInit() {
    this.notificationsSubscription = this.notificationService.getNotificationObservable()
      .subscribe((message) => {
        this.message = message;
        setTimeout(() => this.message = '', 5000); // Hide message after 5 seconds
      });
  }

  ngOnDestroy() {
    if (this.notificationsSubscription) {
      this.notificationsSubscription.unsubscribe();
    }
  }
}
Component to display real-time notifications. It subscribes to the notifications from the NotificationService and displays them. The message is cleared after 5 seconds.