NestJs中回调函数内无法访问this上下文的问题求助
问题:NestJS控制器中
this.httpService.get()报错"Cannot read property 'get' of undefined" 控制器代码
import {ApiTags} from "@nestjs/swagger"; import {Body, Controller, Get, Param, Post, Res,Req} from "@nestjs/common"; import {ReceiptService} from "../service/ReceiptService"; import {ReceiptDto} from "../common/domain/ReceiptDto"; import {Response,Request} from 'express'; import {HttpService} from "@nestjs/axios"; @ApiTags('Receipt') @Controller({version:'1',path:'Receipt'}) export class ReceiptController{ constructor(private readonly receiptService:ReceiptService,private readonly httpService:HttpService) { } @Post() generateReport(@Body() receiptDto:ReceiptDto){ return this.receiptService.getReceiptData(receiptDto.OrderId); } @Get(':OrderId') async displayReceipt(@Param('OrderId') orderId:number,@Res() res:Response,@Req() req:Request){ const data=await this.receiptService.getReceiptData(orderId); res.render('OrderReceipt',{orderData:data},function (err,html) { res.send(html).on('finish',async function (){ const result=await this.httpService.get(`http://localhost:51971/pdfgenerator?url=localhost:4200/v1/Receipt/${orderId}`).bind(this); console.log(result); }); }); } }
错误原因
报错核心是回调函数中的this指向错误:
- 在
res.render和finish事件中使用的普通function会创建独立执行上下文,此时this不再指向ReceiptController实例,而是指向调用该回调的对象(如res对象或事件发射器)。 - 原代码错误地将
bind(this)放在get()调用之后,完全起不到绑定控制器上下文的作用,反而导致逻辑错误。
解决方案
推荐用箭头函数解决,箭头函数不会创建独立的this,会继承外部作用域的this(即控制器实例),修改后的displayReceipt方法如下:
@Get(':OrderId') async displayReceipt(@Param('OrderId') orderId: number, @Res() res: Response, @Req() req: Request) { const data = await this.receiptService.getReceiptData(orderId); res.render('OrderReceipt', { orderData: data }, (err, html) => { res.send(html).on('finish', async () => { const result = await this.httpService.get(`http://localhost:51971/pdfgenerator?url=localhost:4200/v1/Receipt/${orderId}`); console.log(result); }); }); }
其他可选方案
如果偏好使用普通函数,可提前保存控制器的this引用:
@Get(':OrderId') async displayReceipt(@Param('OrderId') orderId: number, @Res() res: Response, @Req() req: Request) { const self = this; // 保存控制器实例的this引用 const data = await this.receiptService.getReceiptData(orderId); res.render('OrderReceipt', { orderData: data }, function (err, html) { res.send(html).on('finish', async function () { const result = await self.httpService.get(`http://localhost:51971/pdfgenerator?url=localhost:4200/v1/Receipt/${orderId}`); console.log(result); }); }); }
内容的提问来源于stack exchange,提问作者Amare Ethiopian
相关产品推荐
相关产品推荐

