我在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;
}
}
现在我如何在任何 Controller 中使用它。如用户、身份验证等。
最佳答案
在嵌套应用模块中注册服务:
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 {}
然后您可以在 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 正在使用 DependencyInjection pattern向 Controller 提供服务,这就是为什么需要在应用程序模块中声明如何提供服务。
关于javascript - 如何在 Nest.js 中注入(inject)普通服务/提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55726844/