简体   繁体   中英

How to Inject plain Service/Provider in nest.js

I made a plain typeScript class in nest.js. JwtTokenService.js

// JwtTokenService.js

import { Injectable, Optional } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from '../modules/auth/interface/jwt-payload.interface';

@Injectable()
export class JwtTokenService {
  constructor(private readonly jwtService: JwtService) {}

  async generateJWT(payload: object): Promise<string> {
    payload['type'] = 'access_token';
    const token = this.jwtService.sign({ payload });
    return token;
  }
}

Now how can I use this in any controller. like user, auth and other.

Register the service in the nest application module:

import { Module } from '@nestjs/common';
import { YourController } from './path-to/your.controller';
import { JwtTokenService } from './path-to/JwtTokenService.service';

@Module({
  controllers: [YourController],
  providers: [JwtTokenService],
})
export class ApplicationModule {}

Then you can use it in your controller:

import { Controller, Get, Post, Body } from '@nestjs/common';
import { JwtTokenService } from './path-to/JwtTokenService.service';

@Controller('your')
export class YourController {
  constructor(private readonly jwtTokenService: JwtTokenService) {}

  @Get()
  async get() {
    // use `this.jwtTokenService`
    ...
  }
}

Nest is using the a DependencyInjection pattern to provide the service to the controller, which is why you need to declare how the service is provided in the application module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM