首页 > 解决方案 > 数字通过从 Angular 客户端到 NestJS 服务器的 Http 请求转换为字符串

问题描述

Number 通过从 Angular 客户端到 NestJS 服务器的 Http 请求转换为字符串:

我将firstIndex: numberGET http 请求的参数从我的 Angular 客户端传递到我的 NestJS 服务器。我到处都把它定义为一个数字。在我的服务功能的参数中firstIndex: number。从服务器端抓取它@Query('firstIndex') firstIndex: number但是当我尝试使用它时,我遇到了问题。当我记录typeof firstIndex它时,它会以字符串形式出现。我必须使用将其转换为数字const firstInd = Number(firstIndex)

我假设这只是与 http 请求本身的性质有关,但我很想知道具体原因。

标签: angularhttpgethttprequest

解决方案


当我开始使用 NestJS 和路由时,我遇到了类似的问题。

然后,在浏览文档和一些开源 NestJS API 项目时,我发现了多种方法来解决这个问题。

  1. 您可以利用ValidationPipe它自动将有效负载转换为您想要的类型。

有两种方法可以做到这一点。

第一个是ValidationPipe在您的控制器方法级别应用。

@Get()
@UsePipes(new ValidationPipe({ transform: true })) // <--- Add this line
getRows(
  @Query('firstIndex') firstIndex: number,
  @Query('limit') limit: number,
  @Query('sorts') sorts: string
){
  console.log(typeof firstIndex === 'number'); // true
  console.log(typeof limit === 'number'); // true
  console.log(typeof sorts === 'string'); // true
}

ValidationPipe在全局级别应用行为的另一种方式。

这就是您在 NestJS App 实例化文件中的操作方式:

app.useGlobalPipes(
  new ValidationPipe({
    transform: true,
  }),
);

ValidationPipe@UsePipes()装饰器是从@nestjs/common包中导入的)

您可以在NestJS Transform payload objects doc中阅读更多相关信息。

  1. 第二种方法是显式转换值的类型。

这是您可以完成的方法:

@Get()
getRows(
  @Query('firstIndex', ParseIntPipe) firstIndex: number, // <-- Added ParseIntPipe
  @Query('limit', ParseIntPipe) limit: number, // <-- Added ParseIntPipe
  @Query('sorts') sorts: string
){
  console.log(typeof firstIndex === 'number'); // true
  console.log(typeof limit === 'number'); // true
  console.log(typeof sorts === 'string'); // true
}

ParseIntPipe@nestjs/common包中导入)

如您所见,在这里,我传递了另一个参数,它是装饰器Pipe中的a 。@Query它会将值解析为整数。

您可以在此处阅读有关NestJS Transform Explicit 转换文档的更多信息。

外部链接:


推荐阅读