将服务添加到自定义路线装饰器Nestjs
我有一个自定义的路线装饰器,该装饰器应该使用服务中的方法,但该服务返回未定义。 typeError:无法读取未定义的
的属性'findcustomer'; 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),
);
是使用装饰器的控制器中的路由,
//Controller
@Get(':orgId')
get(@GetCustomer() customer: Customer) {
return this.organizationService.get(customer.customerId);
}
我可以在装饰函数中调用和使用该服务而无需返回undefined
?
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
;
Fairly new to 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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
错误清楚地告诉了发生了什么事
错误均值
abysionserationservice
是未定义的,并且您正在调用findcustomer
in undefined。这里
让组织服务:组织服务;
您创建一个未定义的变量。您需要先初始化它。
如果您内部有任何依赖性
anduransionsVice
,则需要注入该类对象。如果不只是new Ansuranationservice()
将起作用The error tells clearly what exactly happening
The error means
organizationService
is undefined and you are callingfindCustomer
on undefined.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. if not justnew OrganizationService()
will work