How to pass an array within a query string in HttpClient?

前端 未结 11 895
面向向阳花
面向向阳花 2021-02-02 09:03

This is my array of actors:

[\'Elvis\', \'Jane\', \'Frances\']

How to pass this array within a query strin

11条回答
  •  你的背包
    2021-02-02 09:21

    Works on Angular 6.0.6:

    private getParams(query) {
    let params: HttpParams = new HttpParams();
    for (const key of Object.keys(query)) {
      if (query[key]) {
        if (query[key] instanceof Array) {
          query[key].forEach((item) => {
            params = params.append(`${key.toString()}[]`, item);
          });
        } else {
          params = params.append(key.toString(), query[key]);
        }
      }
    }
    return params;
    

    }

    Result:

    /api/message?page=1&per=2&order_by=name&order_direction=asc&base_object%5B%5D=2&base_object%5B%5D=1
    

提交回复
热议问题