RxJs Subject: Acquiring the Sender

I have been working with Subjects and there is a .subscribe() in a specific class. Emitting values to this class from different other classes has resulted in the subscribe function being triggered multiple times, yet I am unsure of where these emits are coming from.

Is there a method to identify the class or reference from which the emit (.next<T>) was initiated?

Expected behavior:

In the service svc:

obs: Subject<Date> = new Subject<Date>();

Class 1:

svc.obs.next(new Date());

Class n:

svc.obs.next(new Date());

Subscriber:

svc.obs.subscribe((date) => {
        console.log("Triggered from: " + svc.obs.getSource().classname); // Desired output: "Triggered from: SomeNamespace.Classname"
});

Answer №1

You have the option to swap out

obs: Subject<Date> = new Subject<Date>();
with
obs: Subject<any> = new Subject<any>();

After this modification, you can now emit the source on your own

svc.obs.next({ date: new Date(), source: 'whatever source' });

Lastly, when subscribing:

svc.obs.subscribe((data) => {
        console.log("Triggered from: " + data.source + "Date is : "+data.date);
});

Answer №2

A neat solution to tackling this issue is as follows.

Within the service.

// Start by defining an interface like this.
interface ReactiveDate {
    date: Date,
    type: String
}

// Create a Subject using this interface as the generic type.
obs: Subject<ReactiveDate> = new Subject<ReactiveDate>();

Inside your different classes.

// In Class 1.
svc.obs.next({ date: new Date(), type: 'Class 1' });

// In Class 2.
svc.obs.next({ date: new Date(), type: 'Class 2' });

Next, back in your service.

// Implement appropriate logic for "type" within the subscribe callback.
obs.subscribe(({ date, type }) => {
        console.log("Activated from: " + type);
});

By customizing the "type" parameter, you ensure a strong and error-free system since you have predefined values at your disposal. No need for workarounds!

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

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...

Is there a way to adjust this validation logic so that it permits the entry of both regular characters and certain special characters?

Currently, the input field only accepts characters. If any other type of character is entered, an error will be thrown as shown in the code below. How can I update this logic to allow not only letters but also special characters like hyphens and apostrop ...

It seems like there is an issue with your network connection. Please try again

Recently, I made the switch to EndeavourOS, which is based on Archlinux. I completed all my installations without any issues and attempted to create a new NestJs project after installing NVM, Node's latest version, and the NestJs/cli. However, when I ...

Passing extra arguments to a callback function in Typescript

I'm trying to pass a parameter to a callback function. Below is the snippet of my function: let func = function(el, index){ if(el.id === myId) return index; } arr = [obj1, obj2, obj4, ...]; arr.filter(func); Is there a way to suc ...

Why hasn't the variable been defined?

Why am I receiving an error message saying "test is not defined" in this code? Even though I have properly defined the variable in another service file, it seems to be causing issues here. Any insights on what could be going wrong? import { Injectable } f ...

How can I retrieve the decimal x and y coordinates when the mouse is moved in Typescript Angular?

I am in the process of transitioning my user interface from Flash/Flex, where it stores values in decimal format. I need to access and reuse these values. Here is a demo showcasing my problem. Here is a snippet: import { Component, Input } from '@an ...

Encountering errors 'LeftSegment' not found and 'infer' not found within the react-router directory in the node_modules folder

Currently, I am in the process of updating my application from react-router v3 to v6. At the moment, I have successfully installed react-router-dom v6.2.1 as well as react-router v6.2. Additionally, since I am using Typescript, I have also installed @types ...

What is the best way to track events in angular-meteor when a user logs in, logs out, or when there is a change in the user

I am working on meteor-angular and trying to track new user login and logout changes within a single component. I have attempted to subscribe to userData in the component's initialization, but it does not seem to detect when the user logs in or out. I ...

How do I go about updating my custom element after making a REST call using @angular/elements?

Looking for some assistance with my latest creation: import { Component, ViewEncapsulation, OnInit, } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject } from 'rxjs'; @C ...

Problem with Jasmine in Angular 5 within Visual Studio Code

I am completely new to Angular 5 Unit testing and facing some challenges. Despite installing all @types/jasmine, I am encountering errors in my spec.ts file such as 'describle is not a name' and 'jasmine.createSpyObj does not exist on the ty ...

Troubleshooting: Why is Angular2 ngClass malfunctioning?

I am having trouble adding a class based on a condition <tr *ngFor="let time of times; let i = index"> <td [ngClass]="{'red-time':checkInvalid(time['Proles Arrive'])}">{{time['Proles Arrive']}}</td& ...

Ways to carry out two distinct actions following a successful service call with NGRX

I am currently working on a product search feature. The process involves dispatching a 'search_start' action with specific parameters for the search. This action triggers an effect that communicates with a service to retrieve a list of products b ...

Input a new function

Trying to properly type this incoming function prop in a React Hook Component. Currently, I have just used any which is not ideal as I am still learning TypeScript: const FeaturedCompanies = (findFeaturedCompanies: any) => { ... } This is the plain fun ...

Inspecting tRPC routing for examination purposes

Introduction Within my API, it is essential to authenticate the caller following input validation. The authorization for certain endpoints relies on details provided in the input parameters, such as the specific server-side resource being accessed and the ...

Setting up a reverse proxy in Angular 2: A step-by-step guide

My project setup includes: "start": "gulp serve.dev --color", In my service class, I have the following code snippet: this.mapUrl = @apiproxy return this.http.post(this.mapUrl, body, { headers: this.headers }) The Proxy.config.json file contains: { "/ ...

Steps to retrieve a date from a form control

html <form [formGroup]="searchForm" (ngSubmit)="search()"> <div class="row"> <div class="col"> <input type="date" class="form-control" formControlName="startD ...

Is it possible for Typescript interface A to extend B while lacking certain properties from B?

My confusion lies in understanding how TypeScript interfaces function effectively. Here's what I currently have: import type { Socket, Handshake } from 'socket.io'; import type { Session } from './session'; export interface Sessio ...

"Stay tuned for the latest updates on subscribing to Angular

In my Angular 7 code, I am trying to assign the result of a subscription to a specific variable, but it seems like the code is not working as expected. Here is an example of how my code looks: async getItemsbyId(id) { console.log('2') await ...

Import statements cannot be used outside of a module when working with a private npm package in cucumber.js

Utilizing cucumberjs to test various components of my project has been successful. However, I encountered an issue in one step where I utilize a zod schema that is defined within a private npm module: // within the private npm package: // constant.js impor ...

Steps to sending a request with a custom user agent

In my Angular app, I have successfully implemented server-side pre-rendering with the condition that it will only pre-render if a search bot is sending the request. Now, I need to verify if everything is pre-rendered correctly. However, when I visit my w ...