跳到主要内容

装饰器与 Metadata

装饰器​

常用的内置装饰器​

  • @Module: 声明 Nest 模块
  • @Controller:声明模块里的 controller
  • @Injectable:声明模块里可以注入的 provider
  • @Inject:通过 token 手动指定注入的 provider,token 可以是 class 或者 string
  • @Optional:声明注入的 provider 是可选的,可以为空
  • @Global:声明全局模块
  • @Catch:声明 exception filter 处理的 exception 类型
  • @UseFilters:路由级别使用 exception filter
  • @UsePipes:路由级别使用 pipe
  • @UseInterceptors:路由级别使用 interceptor
  • @SetMetadata:在 class 或者 handler 上添加 metadata
  • @Get、@Post、@Put、@Delete、@Patch、@Options、@Head:声明 get、post、put、delete、patch、options、head 的请求方式
  • @Param:取出 url 中的参数,比如 /aaa/:id 中的 id
  • @Query: 取出 query 部分的参数,比如 /aaa?name=xx 中的 name
  • @Body:取出请求 body,通过 dto class 来接收
  • @Headers:取出某个或全部请求头
  • @Session:取出 session 对象,需要启用 express-session 中间件
  • @HostParm: 取出 host 里的参数
  • @Req、@Request:注入 request 对象
  • @Res、@Response:注入 response 对象,一旦注入了这个 Nest 就不会把返回值作为响应了,除非指定 passthrough 为true
  • @Next:注入调用下一个 handler 的 next 方法
  • @HttpCode: 修改响应的状态码
  • @Header:修改响应头
  • @Redirect:指定重定向的 url
  • @Render:指定渲染用的模版引擎

自定义装饰器​

$ nest g decorator decorators/test --no-spec

元数据​

基本使用​

与 Module 的关系​

循环依赖报错的处理​

Module 相互依赖​

如果模块间存在相互依赖的情况就会报错,这是可以通过前置方法 forwardRef 来引用被定义的 Module,forwardRef 会返回目标模块的引用,相当于推迟了两个模块的创建,等到创建好了,返回 Module 的引用

ModuleA
@Module({
imports: [forwardRef(() => ModuleB)],
controllers: [AController],
providers: [AService],
})
export class ModuleA {}
ModuleB
@Module({
imports: [forwardRef(() => ModuleA)],
controllers: [BController],
providers: [BService],
})
export class ModuleB {}

Service 相互依赖​

动态模块​