通过 Angular 客户端到 NestJS 服务器的 Http 请求,数字转换为字符串:
我通过 GET http 请求的参数将 firstIndex: number
从我的 Angular 客户端传递到我的 NestJS 服务器。我到处都将其定义为数字。在我的服务函数 firstIndex: number
的参数中。当从服务器端获取它时 @Query('firstIndex') firstIndex: number
但是当我尝试使用它时,我遇到了问题。当我记录 typeof firstIndex
时,它会以字符串形式出现。我必须使用 const firstInd = Number(firstIndex)
将其转换为数字。
我假设这只是与 http 请求本身的性质有关,但我很想知 Prop 体原因。
最佳答案
当我开始使用 NestJS 和路由时,我遇到了类似的问题。
然后,在查看文档和一些开源 NestJS API 项目时,我发现了多种方法来解决这个问题。
- 您可以利用
ValidationPipe
自动将有效负载转换为您所需的类型。
有两种方法可以做到这一点。
第一个是在 Controller 方法级别应用 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.useGlobalPipes(
new ValidationPipe({
transform: true,
}),
);
(ValidationPipe
和 @UsePipes()
装饰器是从 @nestjs/common
包导入的)
您可以在NestJS Transform payload objects doc中阅读更多相关信息。 .
- 第二种方法是显式转换值的类型。
这是完成它的方法:
@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
包导入的)
正如你所看到的,在这里,我传递了另一个参数,它是 @Query
装饰器中的一个 Pipe
。它将将该值解析为整数。
您可以阅读有关 NestJS Transform Explicit conversion doc here 的更多信息.
外部链接:
关于angular - 通过从 Angular 客户端到 NestJS 服务器的 Http 请求,数字转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68776967/