【问题标题】:Unable to use a decorator into a NestJS service无法在 NestJS 服务中使用装饰器
【发布时间】:2019-09-10 00:43:20
【问题描述】:

为什么我们不能在 NestJS 服务中使用装饰器?这是我尝试做的一个示例,但它不起作用。

装饰器:@User()

// user.decorator.ts
import { createParamDecorator } from '@nestjs/common';

export const User = createParamDecorator((data, req): {userId, email} => {
  return data ? req.user[data] : req.user;
});

当我将此装饰器调用到服务中时,我收到以下消息:在作为表达式调用时无法解析属性装饰器的签名

// connect.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { User } from '../account/user/user.decorator';

@Injectable()
export class ConnectService {
 @User() 
 userInfo;
}

【问题讨论】:

    标签: decorator nestjs


    【解决方案1】:

    看起来您正在尝试在 Injectable() 上添加装饰器,我认为您不能这样做。它需要在一个方法上,这样当它被调用时,一些魔法可以在幕后发生。考虑使用 class-validator 和 validationPipe 例如:

    @Get('vitalsByEncounterID')
    async getVitalsByEncounterID(@Query() params: VitalsByEncounterPathDTO, @Headers(DFDHeaders.xRequestId) requestId: string): Promise<VitalSignsDTO[]> {}
    

    然后你会装饰班级

    export class VitalsByEncounterPathDTO {
      @IsString()
      @IsNotEmpty()
      @ApiModelProperty({ required: true, description: 'iCentra id for the patient' })
      patientId: string;
    
      @IsString()
      @IsNotEmpty()
      @ApiModelProperty({ required: true, description: 'an encounter id for the patient' })
      encounterId: string;
    }
    

    【讨论】:

      【解决方案2】:

      您正在尝试使用 ParamDecorator 装饰属性,这就是您收到此错误消息的原因。

      您能否提供更多有关您的用例的详细信息?这可能会帮助某人就您想要实现的目标提供一些见解。

      【讨论】:

        猜你喜欢
        • 2021-12-27
        • 2023-03-21
        • 2022-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-30
        • 2021-06-08
        • 2022-08-13
        相关资源
        最近更新 更多