php - Angular 查询参数,如 httpd_query_params

标签 php angular http query-string

我目前正在使用带有功能测试的 API。所以我知道我会通过以下网址得到很好的回应:

/api/v1/investisseurs?vehicule%5B0%5D=4

解码后的等效 URL

/api/v1/investisseurs?vehicule[0]=4

使用 Angular 通过 HttpParams 发出我的调用,如下所示

getInvestors(params: HttpParams): Promise<MelodiiaCollectionResponse> {
    console.log(params);
    return <Promise<MelodiiaCollectionResponse>>this.http.get(environment.httpdBackHost + '/investisseurs', {
       params: params,
}).toPromise();

在我的浏览器中出现以下请求的结果

/api/v1/investisseurs?vehicule%5B%5D=%5B%222%22%5D&page=1&max_per_page=15

解码后的等效 URL

/api/v1/investisseurs?vehicule[]=["2"]&page=1&max_per_page=15

问题,如何在 Angular 7 中拥有与 php 方法 http_build_query 相同的查询参数编码?

我想避免自己重新实现轮子:)

提前感谢您的帮助

最佳答案

您可以使用HttpParams构建器通过链接append方法自动解析您的参数。通过一些 reducer ,您可以在 httpParams 中提供数组值

import { HttpParams } from '@angular/common/http';

//Whatever...

getInvestors(vehicules: number[], page: number, maxPerPage: number): Promise<MelodiiaCollectionResponse> {
  const params = vehicules.reduce(
    (previous, vehicule, index) => previous.append(`vehicule[${index}]`, vehicule.toString()),
     new HttpParams()
   )
   .append('max_per_page', maxPerPage.toString())
   .append('page', page.toString())
  return this.http.get<MelodiiaCollectionResponse>(`${environment.httpdBackHost}/investisseurs`, {
     params,
  }).toPromise();
}

关于php - Angular 查询参数,如 httpd_query_params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649264/

相关文章:

php - 错误: showing data in two different places php mysql

angular - @ViewChild 中的读取参数是什么

css - 为什么在 angular2 样式中有一组字符串而不是只有一个字符串?

常规 http 页面中的 https 链接会导致任何问题吗?

http - http.CloseNotify 是否完全被 http.Request.Context().Done() 取代?

asp.net - 如何处理 ASP.NET 站点中的 ASP 请求?

javascript - 谷歌地图记录每一条记录

php - MySQL - "Database name"设置在哪里?

php - 使用一张表将不同的 MIME 类型上传到数据库

angular - Ionic 2 中的谷歌字体