【问题标题】:Passing mutliple query params not working Angular 7 [duplicate]传递多个查询参数不起作用Angular 7 [重复]
【发布时间】:2019-08-06 10:16:20
【问题描述】:
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams} from "@angular/common/http";

export interface Filter {
  countryCode?: string,
  postalCode?: string
}

@Injectable({
  providedIn: 'root'
})
export class CountriesService{

  constructor(private http: HttpClient) { }

  getCountries(filters: Filter) {
    const params = new HttpParams();

    if (filters.countryCode) params.append('countryCode', filters.countryCode);
    if (filters.postalCode) params.append('postalCode', filters.postalCode);

    return this.http.get('/api/countries', {params: params})
  }
}

我有一个从端点获取城市的 Angular 7 http 服务,我想通过 optional 多个查询参数 来过滤服务器端的结果,但它不起作用,但它只适用于一个参数。这些参数被忽略或不传递给请求。

【问题讨论】:

  • 应该是'/api/cities

标签: angular typescript


【解决方案1】:

HttpParams 是不可变的,您可以在此处看到

https://angular.io/api/common/http/HttpParams#description

要添加多个参数,您可以这样做

  getCountries(filters: Filter) {
    let params = new HttpParams();

    if (filters.countryCode) {
      params = params.append('countryCode', filters.countryCode);
    }
    if (filters.postalCode) {
      params = params.append('postalCode', filters.postalCode);
    }

    return this.http.get('/api/countries', {params: params})
  }

比这更好的是,您可以使用参数fromObject 来使代码更清晰。看看吧:

  getCountries(filters: Filter) {
    // you need the '|| undefined' if the value could be empty string
    const paramsObj = {
       countryCode: filters.countryCode || undefined,
       postalCode: filters.postalCode || undefined
    };
    const params = new HttpParams({ fromObject: paramsObj });

    return this.http.get('/api/countries', { params })
  }

【讨论】:

  • 感谢它的工作,fromObject 令人难以置信,我不知道。
  • 是的!根据您的过滤器对象,您可以简单地使用 new HttpParams({ fromObject: filters }) 它有很大帮助
  • 他们为什么这样做。以前版本的 URLsearchparams 比这要好得多。他们正在制造更多的麻烦。
猜你喜欢
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多