In Angular 14, it is crucial to remember that RxJS can only subscribe once within a single component. It is not possible to have

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.

Answer №1

Your issue is quite straightforward, it has nothing to do with RxJS or the subscription.

The problem lies in the fact that you have

<app-notification></app-notification>
included in customer.component.html but it is missing from support.component.html.

To resolve the problem, you need to add

<app-notification></app-notification>
to support.component.html.

Having

<app-notification></app-notification>
in both components will work, however, a more efficient solution would be to move
<app-notification></app-notification>
to app.component.html. This way, you only need to include the component once and it will function across all pages, even if you add more in the future.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

You are unable to call upon an object that may be of type 'undefined' in typescript

Among all the other inquiries on this topic, my issue lies with the typescript compiler seeming perplexed due to the following code snippet: if(typeof this[method] === "function"){ await this[method](req,res,next) } The error message I am en ...

What is the best way to simulate a static variable in JavaScript unit testing?

After running the karma coverage test, I achieved a coverage of 99.3%. To reach 100%, I require assistance in testing the else part of the function below: createCurrencyUnits(): void { var keys = Object.keys(ObjectsDomainConstants.CURRENCY_UNITS); for (va ...

Setting up a routerLink from a component

My current routing is functioning well, however, I am interested in managing the same functionality from a component rather than directly in the HTML. How can I achieve this? HTML <a [routerLink]="[ '..', card.item ]">VIEW MORE</a> ...

Show array elements in Angular framework

I need help with displaying a list that contains three columns: menu, menuItem, and order. The desired display format is to show menu and menuItem ordered by order as follows: Menu 1 : order 200 Menu 2 : order 230 Menu 3 : order 250 Menu item 1 : order 2 ...

Trouble with Angular: mat-sidenav not responding to autosize or mode changes when resized

Currently, I am working on integrating the mat-sidenav into a project. Most of the functionality is working well, but there is one particular issue that arises. When running the app locally in a browser and resizing the window tab multiple times, it opens ...

Error: When trying to run the server using npm, the program returned the message '. is not a recognized command, either internally or externally

I'm currently facing an issue with Angular and npm that I have not been able to resolve yet. The project I am working on can be found at this GitHub repository. While this code has worked for others, it seems like the problem lies on my end. When I r ...

How can items be categorized by their color, size, and design?

[{ boxNoFrom: 1, boxs: [{…}], color: "ESPRESSO", size: "2X", style: "ZIP UP" { boxNoFrom: 13, boxs: [{…}], color: "ESPRESSO", size: "2X", style: "ZIP UP" }, { boxNoFrom: ...

Disabling page transition animation in Ionic 4 / Angular: Step-by-step guide

Is there a way to disable the page transition animation when using 'routerLink' to navigate to a new page? I've searched through the documentation and other sources but couldn't find a straightforward answer. Any guidance on this would ...

Restore the chosen option to its default setting

I have implemented a dynamic selection feature where choosing a value from the first select automatically updates the options in the second select. Here is the HTML code: <select clrSelect name="reviewerTypes" (change)="onChange(currentReviewerType)" ...

Struggling to run my Pact tests using Karma and Angular

I'm struggling to run pact tests with Karma in my Angular app setup. Below is the relevant snippet from my package.json. "@angular/core": "~13.3.6", "@pact-foundation/karma-pact": "^3.1.0", "@pact-foundatio ...

Encountering TS2344 error when referring to the Component Ref in Vue.js during typing operations

I received a component reference on my FormCheckbox component from a patternlib. When I tried to incorporate the component into my own TestComp component, I encountered this TypeScript error that left me puzzled: TS2344: Type '{ name: string; mixins: ...

Guide to incorporating Angular 2 onto a specific section of a webpage

As a student of Angular 2, I have a question about utilizing specific parts of a web page. Is it possible to use certain Angular 2 utilities, such as *ngFor, in only designated areas - for example, within just a div element? While this was feasible in An ...

Is there a way to assign a value to an Angular-specific variable using PHP?

In the development of my Angular 4 application, I encountered an issue while receiving JSON data based on an id value through a PHP script. Upon examining the code, it seems that there should be a value passed into this.PropertiesList. examineProperties(i ...

Angular HTML fails to update correctly after changes in input data occur

Within my angular application, there is an asset creator component designed for creating, displaying, and editing THREE.js 3D models. The goal was to implement a tree-view list to showcase the nested groups of meshes that constitute the selected model, alo ...

What could be causing my function to not provide the expected output?

Whenever I try to invoke the function from another part of the code, I encounter an issue where it returns undefined before actually executing the function. The function is stored in a service. login.page.ts: ngOnInit(){ console.log(this.auth.getRole()) ...

What is the best way to create a props interface that includes state and setState values that are being

As I dive deeper into TypeScript, a hurdle has appeared in my app. Upon introducing React.FunctionComponent to my components, an issue arose with my Props interface. The error message reads: Type '({ value, setValue, }: Props) => JSX.Element' ...

Failed validation for Angular file upload

I attempted to create a file validator in the front end using Angular. The validator is quite straightforward. I added a function onFileChange(event) to the file input form to extract properties from the uploaded file. I then implemented a filter - only al ...

There is a metadata version mismatch detected in the module located at /var/www/html/idi/client2/node_modules/@ng-idle/keepalive/index.d.ts

i just included ng-idle/keepalive. below is the content of my package.json file { "name": "azimuth", "version": "1.1.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", ...

Angular provides a convenient way to retrieve data from multiple observables by using the mergeMap

I am currently working on implementing multiple http service calls in an Angular project. I have a requirement to fetch data from 4 different sources using these http services. Within my component, I am making service calls like this: app.component.ts en ...

Is it possible to retrieve all mandatory attributes of a TypeScript object?

Is there a method or approach available that can retrieve all necessary properties from a TypeScript interface or an object? For instance, something along the lines of Object.getOwnPropertyDescriptors(myObject) or keyof T, but with the specific details o ...