javascript - 如何在 Nest.js 中注入(inject)普通服务/提供者

标签 javascript typescript nestjs

我在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/

相关文章:

javascript - 将base64编码的字符串解码为xls

javascript - NestJS 环境变量未定义

nestjs - 如何在 Nestjs DatabaseModule 中使用 ConfigService

javascript - Windows 7 小工具不释放 ActiveX 对象

angular - Ionic 2 ngFor更新 View 中的数据

reactjs - 下拉 onchange 不起作用 : React+ Typescript+ semantic-ui-react

javascript - 如何从 EventEmitter 监听器函数调用 NestJs 微服务?

javascript - 如何从使用 Google Charts 生成的组合图表中删除网格线

javascript - 移动网站的滚动助手

javascript - 跳转到图像 map 上的特定位置