当使用相同的密钥生成查询参数时,Angular HttpParams是否有一种方法可以为序列化查询参数添加方括号?

时间:2017-11-26 14:51:16

标签: angular angular-http

当使用相同键但多个值的多个查询参数查询我的api时,它不能正确解释请求,除非向每个键添加方括号。让我举个例子:

    let params = new HttpParams();

    params = params.append('color', 'blue');
    params = params.append('color', 'red');

    console.log(params.toString()) // color=blue&color=red 
    // Would prefer color[]=blue&color[]=red

有没有办法产生这种功能?

2 个答案:

答案 0 :(得分:0)

我通过编写自己的拦截器并使用另一个库生成查询字符串来解决这个问题。请参阅以下内容:

安装此库:

$ npm i query-string --save

添加此拦截器:

import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpParams,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import * as querystring from 'query-string';

@Injectable()
export class QueryParamInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (!request.params.keys().length || request.method !== 'GET') {
      return next.handle(request);
    }

    let { params } = request;

    let queryParams = this.createQueryParams(params);

    let queryString = querystring.stringify(queryParams, { arrayFormat: 'bracket' });

    let urlWithParams = request.urlWithParams.replace(request.params.toString(), queryString);

    request = request.clone({
      url: urlWithParams,
      params: new HttpParams(),
    });

    return next.handle(request);
  }

  private createQueryParams(params: HttpParams): { [key: string]: string } {
    let queryParams = {};

    for (let key of params.keys()) {
      let values = params.getAll(key);

      if (!values) {
        continue;
      }

      if (values.length === 1) {
        queryParams[key] = values[0];

        continue;
      }

      queryParams[key] = values;
    }

    return queryParams;
  }
}

答案 1 :(得分:0)

您可以覆盖angulars'HttpParameterCodec不对方括号进行编码:

export class MyCustomHttpUrlEncodingCodec extends HttpUrlEncodingCodec {
    encodeKey(k: string): string {
        return super.encodeKey(k)
            .replace(new RegExp("%5B", "g"), "[")
            .replace(new RegExp("%5D", "g"), "]");
    }
}

我在这里详细描述了我的解决方案:http://www.moritz-benzenhoefer.com/angular-http-requests-use-square-brackets-in-httpparams-as-parameter-key-name/