How can you utilize an injected service from inside a Class decorator in Typescript/NestJS?

Can an injected service be accessed from within a Class decorator?

I aim to retrieve the service in the personalized constructor:

function CustDec(constructor: Function) {
  var original = constructor;

  var f: any = function (...args) {
    // How can I access the injectedService here?
    // I have attempted things like this.injectedService but without success
    return new original(...args);
  }

  f.prototype = target.prototype;
  return f;
}

@CustDec
@Injectable()
class MyService {
  constructor(
    private readonly injectedService: InjectedService,
  ) {}
}

Answer №1

After referring to the official documentation on class decorators, here is a method that should be effective:

function CustomDecorator<T extends new(...args: any[]) => {}>(Target: T) {
    return class extends Target {
        constructor(...args: any[]) {
            super(...args);
            (args[0] as InjectedService).doSomething();
        }
    }
}

@CustomDecorator
@Injectable()
class MyService {
  constructor(
    private readonly injectedService: InjectedService,
  ) {}
}

I have also provided an example in this TS Playground link.

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

Obtaining undefined values for req and resolvedUrl in GetServerSideProps function

In my project, I am currently using next.js version ""next": "^12.1.4"" and node version ""@types/node": "^14.14.6". I have created a function called getServerSideProps with parameters req and resolvedUrl. When the ...

The viewport width in NextJS does not extend across the entire screen on mobile devices

I'm currently tackling a challenge with my NextJS Website project. It's the first time this issue has arisen for me. Typically, I set the body width to 100% or 100vw and everything works smoothly. However, upon switching to a mobile device, I not ...

What is the best way to transfer a variable between components in Angular without using the HTML page, directly within the components themselves?

Within the child component, I am working with a string: @Input() helloMessage:string; I am looking to assign a value to this string from another string in the parent component and utilize it within the child component without displaying the value in the h ...

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

The type 'string' cannot be assigned to the type 'T[keyof T]' within this context

I have a function that processes an array of Episodes and assigns data from an external file to the corresponding Episode based on a specified keyName: const assignDataFromExternalFile = (arrayToProcess: Episode[], filePath: string, keyName: keyof Episode) ...

What is the reason for the typescript check failing?

When attempting to check for the existence of an attribute using if statement, I encountered an error. Can anyone explain why this happened? I would appreciate any insights on this issue. ...

Exclude all .js files from subdirectories in SVN

In my typescript project, I am looking to exclude all generated JavaScript files in a specific folder from SVN. Is there a convenient command or method to achieve this for all files within the directory? ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

Improving JavaScript Functions: Minimize duplication of helper methods

I have a set of helper functions that check for the presence of specific strings in an array and certain steps before triggering other functions. The reason for keeping them separated is because arrTours must be associated with only those arrSteps. // Help ...

Getting an error message with npm and Typescript that says: "Import statement cannot be used outside

After developing and publishing a package to npm, the code snippet below represents how it starts: import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; export interface ... export class controlplaneDependencies ...

The `Home` object does not have the property `age` in React/TypeScript

Hey there, I'm new to React and TypeScript. Currently, I'm working on creating a React component using the SPFX framework. Interestingly, I'm encountering an error with this.age, but when I use props.age everything seems to work fine. A Typ ...

Building a resolver to modify a DynamoDB item via AppSync using the AWS Cloud Development Kit (CDK)

After successfully creating a resolver to add an item in the table using the code provided below, I am now seeking assistance for replicating the same functionality for an update operation. const configSettingsDS = api.addDynamoDbDataSource('configSet ...

The alias for the computed column is not correctly connected to the TypeORM Entity

I am currently working on extracting data from a table in a MySQL database using TypeORM for my Express.js project. In order to retrieve the data, I am utilizing the QueryBuilder. This is the implementation I have: const result = await this.repository.cr ...

Encountering an error: "Unable to assign the 'id' property to an undefined object while attempting to retrieve it"

I'm running into an issue while attempting to retrieve a specific user from Firebase's Firestore. export class TaskService { tasksCollection: AngularFirestoreCollection<Task>; taskDoc: AngularFirestoreDocument<Task>; tasks: Obs ...

Angular 2's abstract component functionality

What are the benefits of utilizing abstract components in Angular 2? For example, consider the following code snippet: export abstract class TabComponent implements OnInit, OnDestroy {...} ...

Having an issue in Angular 2 where the correct function is not triggered when a button is placed within a selectable anchor

Within an anchor element, I have a button that triggers its own click listener for an editing popup module. The anchor itself has another click listener assigned to it. For example: <a (click)="onClick(myId)" class="list-group-item clearfix"> < ...

What is the best approach to organize data from an observable based on a nested key?

I'm currently developing a new application and struggling with grouping data. The data is being pulled from an observable, and I need to group objects by their status and push them into an array. I attempted to use the groupBy() method, but unfortunat ...

There was an error encountered: Uncaught TypeError - Unable to access the 'append' property of null in a Typescript script

I encountered the following error: Uncaught TypeError: Cannot read property 'append' of null in typescript export class UserForm { constructor(public parent: Element) {} template(): string { return ` <div> < ...

Error when compiling TypeScript: The callback function provided in Array.map is not callable

This is a Node.js API that has been written in Typescript. app.post('/photos/upload', upload.array('photos', 12), async (req, res) => { var response = { } var list = [] try { const col = await loadCollection(COLLECTION_NAM ...

Is there a way for me to navigate from one child view to another by clicking on [routerLink]?

Currently, I am facing an issue with switching views on my Angular website. The problem arises when I attempt to navigate from one child view to another within the application. Clicking on a button with the routerlink successfully takes me to the new view, ...