How to pass URLSearchParams in the HttpClient "get" method - Angular 5

mike picture mike · Nov 29, 2017 · Viewed 48.7k times · Source

I used Angular 4.2 with the Http service and I used the get method like this where params is a URLSearchParams object:

this.http.get(url, {headers: this.setHeaders(), search: params})

I want to migrate to Angular 5. http is now a HttpClient object like recommended by the angular team. I got an error with the 'search' key.

Do you know how to migrate Http to HttpClient service in my case?

Thank you.

Answer

Bougarfaoui El houcine picture Bougarfaoui El houcine · Nov 29, 2017

Since Angular 4.3 you can use HttpClient like this :

import { HttpClient,HttpHeaders, HttpParams } from '@angular/common/http';

   constructor(private httpClient: HttpClient) { }    

   getData(){
        let headers = new HttpHeaders();
        headers  = headers.append('header-1', 'value-1');
        headers  = headers.append('header-2', 'value-2');

       let params = new HttpParams();
       params = params.append('param-1', 'value-1');
       params = params.append('param-2', 'value-2');

       this.httpClient.get("/data", {headers , params })
   }

HttpParams and HttpHeaders are immutable classes so after each call of set or append methods they return a new instance that's why you should do this : params = params.append(...)