nipek
nipek

Reputation: 850

[NestJS]Custom Parameter in Class Constructor

I am trying to pass custom arguments into a class that injects another service(ApiCallService).

export class FPCT {    
  constructor(
    payload: {
      isLive: boolean;
      exchangeReference?: string | number;
    },
    private apiCallService: ApiCallService,
  ) {}
}

ApiCallService is already added to the module provider but the service keeps returning undefined when I try to access it.

I have tried to add the FPCT class as a provider but nest complains about it not being able to define the first parameter(the payload object)

The first parameter(the payload object) is going to be passed from a controller

Upvotes: 1

Views: 1207

Answers (1)

Micael Levi
Micael Levi

Reputation: 6685

You could write it like this:

@Module({
  providers: [
    FPCT,
    ApiCallService,
    {
      provide: 'payload',
      useValue: {
        isLive: true,
        exchangeReference: '1234',
      },
    },
  ],
})
export class MyModule {}
// ...
@Injectable()
export class FPCT {
  constructor(
    @Inject('payload')
    payload: {
      isLive: boolean;
      exchangeReference?: string | number;
    },
    private apiCallService: ApiCallService,
  ) {}
}

You could use ModuleRef#get, or app.get(ApiCallService).

It all depends on what you're trying to do, which wasn't clear.

Upvotes: 1

Related Questions