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

时间:2018-12-21 20:26:15

标签: angular

我有这种代码,在这里我要为查询参数请求一个带有空字符串的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())
    });
  }

调用 getArticles 函数后,我得到了以下网址之王:127.0.0.1:8000/api/articles?page=1&per_page=6&query=
问题是:如果有空字符串,是否有任何干净的方法可以使query参数不会出现在url中?

2 个答案:

答案 0 :(得分:0)

我很好奇空白值是否会影响您的查询结果。无论如何,如果确实很麻烦,您可以编写一个函数以仅添加查询参数(如果存在)。例如

'''
Test program to use P12 credentials with Google Cloud Storage
'''
from oauth2client.service_account import ServiceAccountCredentials
import googleapiclient.discovery

# Details on the Google Service Account. The email must match the Google Console.
project_id = 'development-123456'
sa_filename = 'compute-engine.p12'
sa_password = 'notasecret'
sa_email = 'development-123456@developer.gserviceaccount.com'

SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]

cred = ServiceAccountCredentials.from_p12_keyfile(
        sa_email,
        sa_filename,
        private_key_password=sa_password,
        scopes=SCOPES)

client = googleapiclient.discovery.build('storage', 'v1', credentials=cred)

buckets = client.buckets().list(project=project_id).execute()

print('')
print('Listing buckets:')
for bucket in buckets['items']:
    print(bucket['name'])

答案 1 :(得分:0)

我刚刚创建了一种函数来迭代我的参数并删除未定义的和null的函数。我们所需要做的就是导入定义函数的文件,然后再传递必要的参数作为参数。

print()

如果我们这样请求:

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] }) );