Search code examples
typescriptdependency-injectionnestjs

Inject a service inside another service in Nestjs?


I need something like this:

@Injectable()
class TokenVerification {
    verify(token: string) {
        //...
    }
}

//Inject TokenVerification into MailService
@Injectable()
export class MailService {

    public constructor(private tokenVerification: TokenVerification) {}

    public sendMail() {
        // ...
    }

    public verifyEmail(token: string) {
        this.TokenVerification.verify(token);
    }
}

Later, I will inject the MailService into a controller using a module:

@Module({
  imports: [],
  providers: [MailService],
  controllers: [SomeController],
})
export class SomeModule {}

How can I achieve injection between classes or services in NestJS? :)


Solution

  • you need to add the services to SomeModule providers like you did in your question example and in the some.service.ts

    you use it this way in your constructor

    constructor(
     private readonly mail: MailService,
    ) {}