代码之家  ›  专栏  ›  技术社区  ›  famas23

HttpParams不使用空字符串发送参数

  •  0
  • famas23  · 技术社区  · 7 年前

    我有这样的代码,其中我为查询参数请求一个带有空字符串的API:

      getArticles(params?: HttpParams): Observable<any> {
        return this.http.get(this._articlesUrl, {
          params:  new HttpParams()
            .set('page', this.page.toString())
            .set('per_page', this.limit.toString())
            .set('query', this.query.toString())
        });
      }
    

    获取文章 函数,我得到了这个url之王: 127.0.0.1:8000/api/articles?page=1&per_page=6&query=
    问题是:有没有什么干净的方法可以让 query 如果是空字符串,则参数不会出现在url中?

    2 回复  |  直到 7 年前
        1
  •  1
  •   famas23    7 年前

    import {HttpParams} from '@angular/common/http';
    
    export function createHttpParams(params: {}): HttpParams {
        let httpParams: HttpParams = new HttpParams();
        Object.keys(params).forEach(param => {
            if (params[param]) {
    
                if (params[param] instanceof Array) {
                    params[param].forEach(value => {
                        httpParams = httpParams.append(param, value);
                    });
                } else {
                    httpParams = httpParams.append(param, params[param]);
                }
            }
        });
    
        return httpParams;
    }
    

    如果我们提出这样的要求:

    this.http.get('/api/articles', createHttpParams({
                    'page': this.page,
                    'per_page': this.limit,
                    'query': this.query, //null or undifined
                    'suppliers[]': this.suppliersIds //[1,4]
                })
            );
    

    我们的最终url将如下所示 ../api/articles?page=1&per_page=5&suppliers[]=1&suppliers[]=4

        2
  •  0
  •   corytak    7 年前

    我很好奇空白值会影响查询结果。不管怎样,如果真的有问题,您可以编写一个函数,只在查询参数存在时添加查询参数。例如

    private setQueryParams(): HttpParams {
        const params = new HttpParams();
        if (this.page) {
           params.set('page', this.page.toString());
        }
        ...etc
        return params;
    }
    
    推荐文章