mike mike - 6 months ago 132
HTTP Question

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

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 Source

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('header-1', 'value-1');
       params = params.append('header-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 returns a new instance that's why you should do this : params = params.append(...)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download