When using Rxjs in Angular 14, it's important to note that subscription occurs only once in a single component, not across different components simultaneously.
Project Description
I am currently developing a notification service for my application. Whenever a customer submits a case, it is assigned to a support team. I need to notify both the customers and the support team at the same time or within a 1-2 second duration using WebSockets.
Here is the code snippet from Notification.service.ts
:
import { Injectable } from '@angular/core';
import { Subject, Observable } from "rxjs";
import { Notification, NotificationType } from "../models/notification.model";
@Injectable()
export class NotificationService {
private _subject = new Subject<Notification>();
private _idx = 0;
constructor() { }
getObservable(): Observable<Notification> {
return this._subject.asObservable();
}
info(title: string, message: string, timeout = 3000) {
this._subject.next(new Notification(this._idx++, NotificationType.info, title, message, timeout));
}
// Other methods like success, warning, and error follow similar pattern...
}
In the Notification component, the subscription is implemented as shown below:
notification.ts
import { debounceTime, Subscription } from "rxjs";
private _subscription: Subscription;
constructor(private _notificationSvc: NotificationService) { }
this._subscription = this._notificationSvc.getObservable().pipe(debounceTime(1000)).subscribe((notification) => {
console.log("Received Notification: ", notification);
this._addNotification(notification)
});
Websockets code excerpt:
import { Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
// Other imports...
@Injectable()
export class WebSocketService {
// Class implementation...
}
No errors have been encountered during development.
Issue
The problem arises when notifications are received by customers but not by members of the support team. This discrepancy is due to the fact that the Rxjs subject subscribes only once in a single component, rather than across multiple components simultaneously.
To watch a video explanation of this issue, visit: https://www.youtube.com/watch?v=R5dhCUC3x5s
GitHub repository link: https://github.com/codeztech-atique/angular-websockets-testing-api
Access the project on StackBlitz: https://stackblitz.com/edit/angular-ivy-eiqr8u
Any assistance or guidance on resolving this issue would be greatly appreciated as I am relatively new to this concept. Please feel free to provide any insights or suggestions to help address this challenge.