Enhance a subject's behavior by overriding the .next method using a decorator

Currently, I am working on an Angular application where I have numerous Subjects, BehaviorSubjects, and ReplaySubjects as properties in various services. I am attempting to create a TypeScript decorator that can be added to some of these Subjects to enhance functionality when the .next function is called on them, specifically to manually trigger a global change detection.

@Injectable({
    providedIn: 'root',
})
export class MyService extends HttpService {

    @TriggerGlobalChangeDetection
    public mySubject$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}

Here is the content of the decorator.ts:

// export function TriggerGlobalChangeDetection(): (Target: any, propertyKey: string) => {
//     const origNext = Target.prototype.next;
//     Target.prototype.next = function () {
//         console.log('overriding next');
//         origNext.apply(this);
//         GlobalChangeDetectionService.detectChanges();
//     };
// };

export function TriggerGlobalChangeDetection(
    target?: any,
    propertyName?: string,
    descriptor?: PropertyDescriptor
) {
    const origNext = target.prototype.next;
    console.log('overriding next');
    origNext.apply(this);
    GlobalChangeDetectionService.detectChanges();
}

// export const TriggerGlobalChangeDetection = (Target: any, p: string): any => {
//     return class extends Target {
//         next = (value: any): void => {
//             super.next(value);
//             GlobalChangeDetectionService.detectChanges();
//         };
//     };
// };

I have tried different implementations of the decorator, but all have failed due to the exception thrown by Target.prototype.next. It seems that Target is of type HttpService, which may be why I cannot access mySubject$.

If anyone has suggestions on how to make this work, I would greatly appreciate it.

Best regards, Simon

Answer №1

Consider implementing the following approach:

class CustomService {

  
  private _customSubject$ = new BehaviorSubject<Boolean>(false);

  get customSubject(): Observable<Boolean> {
    return this._customSubject$;
  }

//.... whether it's in constructor or a function
        if (some condition = true) {
          this._customSubject$.next(true);
        } else {
          this._customSubject$.next(false);
        }
  

Utilize CustomService.customSubject in various components or as required.

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

The error message "Can't resolve all parameters for CustomerService" is preventing Angular from injecting HttpClient

I have a customerService where I am attempting to inject httpClient. The error occurs on the line where I commented //error happens on this line. Everything works fine until I try to inject httpClient into my service. The error message is: `compiler.js: ...

Tips on transferring data to a parent component without dismissing the Angular Material dialog when a button is clicked

Is there a way to transfer data from a popup (angular material dialog) to its parent component when a button is clicked, all without closing the popup window? I'm stumped on how to accomplish this task. If anyone knows a solution, please lend me a ha ...

Ensure the proper sequence of field initialization within a TypeScript class constructor

Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors? In this example (run), this.x is accessed in the method initY before it's initialized in the constructor: class A { readonly x: number rea ...

Evaluating file selection and uploading functionality within Spectron

Currently, I am faced with the challenge of writing a test for an electron GUI that includes a choose file dialog. Unfortunately, I do not have access to the inner workings of the GUI. Here is the code snippet I have written: await app.client.chooseFile( ...

Continuous HTTP Stream Observable that only transfers data without emitting any other items

I've encountered an issue while working with Angular 4 and RxJS. In my code, the Observable generated by the http.post request is not passing any data to the subsequent map() function. The POST request seems to result in an endless stream of Motion JP ...

Issue in Angular: Attempting to access properties of undefined (specifically 'CustomHeaderComponent')

I have encountered a persistent error message while working on a new component for my project. Despite double-checking the injection code and ensuring that the module and component export logic are correct, I am unable to pinpoint the issue. custom-header ...

Issue arising from passing an object through a component in a Next.js application during build time when the object is retrieved from a database

Can anyone provide assistance with solving this issue? I have an object called "diary" coming from a database, which is passed to a component where a useState hook is expecting that object. During build time, the following error is occurring. An error is ...

What is causing my React-Testing Library queries to not work at all?

In my current project, I am using Jest along with Testing-Library to create UI unit tests. One issue that I encountered was that the components were not rendering on the DOM. After some investigation, I found that the main culprit was a component called & ...

The UI in PrimeNG dropdown does not reflect changes made with patchValue()

Currently, I am working on a reactive form that includes a few fields - three dropdowns and one calendar. These fields are all PrimeNG components. Interestingly, all fields except for the project field successfully update their values in the user interface ...

Unsuccessful file uploads with Angular using multer and Node/Express

Currently, I am facing an issue with single file upload using multer. While I can manually upload a file to the specified folder in the backend using tools like postman for testing the express route, the same functionality fails when trying to upload it th ...

Creating Excel documents using Angular and XLSX template generator

In my Angular application, I am utilizing the XLSX library to manipulate an Excel file. The file I start with is encoded in base64 format, so my first task is to decode it, make some changes to specific cells, and then save the modified file back in base64 ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

Creating a constructor that assigns values by using interfaces that are built upon the class

Looking at this interface/class example export interface MyErrorI { something: boolean; } export class MyError extends Error implements MyErrorI { public something = false; constructor(message: string, key: keyof MyErrorI ) { super(m ...

Utilizing Angular with the development environment of Visual Studio 2015

Having trouble setting up my angular 2 application in visual studio 2015 (with update 1). The typescript compile is throwing an error - it says 'Cannot find module '@angular/core' at import { NgModule } from '@angular/core';. I eve ...

Navigation arrows for sliding`

Is there a way to add custom right/left arrows to the Ionic slider component? Demo: Check it out on Stackblitz Note: Make sure to refer to the home.html page for more details. https://i.sstatic.net/jQ62l.png .html <ion-slides [pager]="true" [slide ...

Fetching deeply nested data from JSON within Angular Material tables - ANGULAR

Having trouble retrieving data from localhost, especially when it's in a different structure. Any suggestions on how to properly extract and display this data for the user? This is my attempted approach, but I'm encountering an error message: ER ...

Property input not being refreshed upon using callback function

One challenge I am facing is updating a property in a child component whenever there is a push notification from Firebase. Everything seems to be set up correctly with Firebase and the property as an input in the child component. Interestingly, when I manu ...

What is the best way to create an array of strings that can include multiple elements from a set of strings?

Exploring different roles for authorization: ['admin', 'manager', 'user'] Is there a way to create a specific type, named Roles, which is essentially a string array ( string[] ) that is limited to only containing values from ...

What makes a pristine form essential in angular at all times?

Here is the code snippet: <form #userForm="ngForm" (ngSubmit)="save(userForm)"> <input type="email" #contactEmail="ngModel" email minlength="2" [(ngModel)]="contactInformation.email" class="form-control" id="contactEmail" name="contactEmail" ...