1
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})
  }
}

I have an Angular 7 http service that fetches cities from an end point, I want to pass optional multiple query params to filter the results on the server side but it doesnt work however it works with just one param. These params are being ignored or not passed to the request.

1 Answers1

2

The HttpParams is immutable as you can see here

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

To add multiple params you could do

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

Better than this, there is the param fromObject that you may use to make the code cleaner. Check it out:

  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 })
  }
Leandro Lima
  • 1,164
  • 6
  • 12