网站搜索

javascript - 如何在 nest.js 中注入普通的服务/提供者


我在 nest.js 中创建了一个普通的 TypeScript 类。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;
  }
}

现在我如何在任何控制器中使用它,比如用户、认证和其他控制器。

答案#1

在 nest 应用模块中注册该服务:

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 {}

然后你可以在你的控制器中使用它:

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 使用依赖注入模式将服务提供给控制器,这就是为什么你需要在应用程序模块中声明服务的提供方式。