简体   繁体   English

将服务添加到自定义路由装饰器 nestjs

[英]Add A Service to Custom Route Decorator nestjs

I have a Custom Route Decorator which is suppose to use a method from a Service but the service returns undefined.我有一个自定义路由装饰器,它假设使用服务中的方法,但服务返回未定义。 TypeError: Cannot read property 'findCustomer' of undefined ; TypeError: Cannot read property 'findCustomer' of undefined Fairly new to nestjs对nestjs相当陌生

//Custom Route Decorator - CustomerDecorator

export async function getCustomerFromExeContext(
  context: ExecutionContext,
): Promise<Customer> {
  let organizationService: OrganizationService;
  const req = context.switchToHttp().getRequest<Request>();

  if (!req.params.orgId)
    throw new HttpException('OrgId not found', HttpStatus.UNAUTHORIZED);

  const customer = await organizationService.findCustomer(
    parseInt(req.params.orgId),
  );
  if (!customer) {
    throw new HttpException('Customer not found', HttpStatus.NOT_FOUND);
  }
  return customer;
}

export const GetCustomer = createParamDecorator(
  (_, context: ExecutionContext) => getCustomerFromExeContext(context),
);

This is the Route within the controller that utilize the Decorator这是控制器中使用装饰器的路由

//Controller

@Get(':orgId')
  get(@GetCustomer() customer: Customer) {
    return this.organizationService.get(customer.customerId);
  }

Is there a way I can call and use the service within the decorator function without returning undefined ?有没有一种方法可以在装饰器函数中调用和使用服务而不返回undefined

The error tells clearly what exactly happening该错误清楚地说明了到底发生了什么

TypeError: Cannot read property 'findCustomer' of undefined TypeError:无法读取未定义的属性“findCustomer”

The error means organizationService is undefined and you are calling findCustomer on undefined.该错误表示未定义organizationService ,您在未定义时调用findCustomer

Here这里

let organizationService: OrganizationService;

you create an undefined variable.您创建了一个未定义的变量。 you need to initialize it first.你需要先初始化它。

If you have any dependency inside OrganizationService then you need to inject that class object.如果您在OrganizationService中有任何依赖项,那么您需要注入该类对象。 if not just new OrganizationService() will work如果不只是new OrganizationService()将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM