angular - 数字通过从 Angular 客户端到 NestJS 服务器的 Http 请求转换为字符串
问题描述
Number 通过从 Angular 客户端到 NestJS 服务器的 Http 请求转换为字符串:
我将firstIndex: number
GET http 请求的参数从我的 Angular 客户端传递到我的 NestJS 服务器。我到处都把它定义为一个数字。在我的服务功能的参数中firstIndex: number
。从服务器端抓取它@Query('firstIndex') firstIndex: number
但是当我尝试使用它时,我遇到了问题。当我记录typeof firstIndex
它时,它会以字符串形式出现。我必须使用将其转换为数字const firstInd = Number(firstIndex)
。
我假设这只是与 http 请求本身的性质有关,但我很想知道具体原因。
解决方案
当我开始使用 NestJS 和路由时,我遇到了类似的问题。
然后,在浏览文档和一些开源 NestJS API 项目时,我发现了多种方法来解决这个问题。
- 您可以利用
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中阅读更多相关信息。
- 第二种方法是显式转换值的类型。
这是您可以完成的方法:
@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 转换文档的更多信息。
外部链接:
推荐阅读
- python - 在 Python 上,我无法使用 pip install beautifulsoup4 安装 beautifulsoup 4 4.9.3
- python - 内存高效切片numpy数组
- python - Python - 如何根据用户输入更改字典中的值?(“关上盒子”游戏)
- node.js - 我在反应中使用 axios post 时遇到问题
- javascript - 表单提交错误说明.then 不是错误
- python - 如何让 Python 中的多个变量通过站点包中的相同函数运行?
- c# - `WhenAll(TaskList)` 和 `WhenAll(TaskList).Wait()` 有什么区别?
- asp.net-core - 如何从调用使用 .NET Core 3 构建的 API 的 react js 内置网站生成和/或获取 access_token 和 refresh_token?
- javascript - 如何使用 javascript 在 html5 中播放视频时产生负音频延迟?
- php - 尝试从 wp_posts 获取唯一事件列表以及来自 wp_postmeta 的数据