menu

Questions & Answers

Rxjs subscribes only once, in 1 component, not same time diff components in angular 14

Rxjs subscribes only once, in 1 component, not the same time diff components in angular 14.

Requirements -

I am building a notification service, when any customer, submits any case, it's assigned to a support team, and I want to notify customers and the support team at the same time, or 1-2 sec duration, I am using the WebSockets here.

Code - 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));
  }

  success(title: string, message: string, timeout = 3000) {
    this._subject.next(new Notification(this._idx++, NotificationType.success, title, message, timeout));
  }

  warning(title: string, message: string, timeout = 3000) {
    this._subject.next(new Notification(this._idx++, NotificationType.warning, title, message, timeout));
  }

  error(title: string, message: string, timeout = 0) {
    this._subject.next(new Notification(this._idx++, NotificationType.error, title, message, timeout));
  }

}

In the Notification component, I subscribe like this -

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("I am notification called: -", notification);
            this._addNotification(notification)
        });

Error: - There are no error

Problem -

I am getting notifications for the customer, not for the support team member. Because the Rxjs subject, subscribes only once, in 1 component, not same time diff components.

Any help would be appreciated.

Comments:
2023-01-17 20:42:03
Have you tried a BehaviorSubject in place of a Subject? It will provide a notification to any late subscribers. (The code shown above doesn't really show customer vs support team members, so I'm a bit unclear where you may have a problem. Any way you could do a short Stackblitz that demonstrates the actual issue?)
Answers(0) :