angular - 通过从 Angular 客户端到 NestJS 服务器的 Http 请求,数字转换为字符串

标签 angular http get httprequest

通过 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 项目时,我发现了多种方法来解决这个问题。

  1. 您可以利用 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/

    相关文章:

    html - 错误 : ExpressionChangedAfterItHasBeenCheckedError

    angular - 类型 'Observable<boolean>' 不可分配给类型 'Observable<BreakpointState>'

    angular - 模板中的 ngIf-else

    javascript - 如何使用 javascript 拦截站点 http 请求?

    android - 即使模型正确,来自 API 的响应也不会映射到对象

    angular - 如何为多个应用程序捆绑可重用的 angular 2 组件?

    c - 如何在没有 libcurl 的情况下在 C 中发出 HTTP get 请求?

    r - 如何从具有基本 HTTP 身份验证的 URL 下载大型 csv 文件到具有 R 的数据框中

    PHP:嵌入另一个 URL 的 URL 的较短/模糊编码?

    wordpress - 如何在 WordPress 中使用 ajax 发送大量 POST 数据?