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服务,可从端点获取城市,我想通过可选 多个查询参数在服务器端过滤结果,但是不起作用,但是仅适用于一个参数。这些参数将被忽略或不传递给请求。
答案 0 :(得分:0)
您可以在此处看到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 })
}