How to pass URLSearchParams in the HttpClient "get" method - Angular 5
Solution 1
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(...)
Solution 2
Angular 4 Way:
this.http.get(url, {headers: this.setHeaders(), search: params})
Angular 5 Way:
import { HttpClient, HttpParams } from '@angular/common/http';
let params = new HttpParams().set('paramName', paramValue);
this.http.get(url, { params: params })
Multiple Params:
// Initialize Params Object
let Params = new HttpParams();
// Begin assigning parameters
Params = Params.append('firstParameter', firstVal);
Params = Params.append('secondParameter', secondVal);
Solution 3
Following will be the changes, you need to do:
Replace Older Http import with:
import { HttpClient } from "@angular/common/http";
Create HttpClient object as below:
constructor( protected httpClient: HttpClient, ) {}
Now there are ways to achieve search parameter namely as below:
public get(searchParam: string): Observable { return this.httpClient.get(
${this.URL}/${searchParam}
); }
or:
public get(searchParam: string): Observable<object> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let myParams = HttpParams().set("id", searchParam);
let options = new RequestOptions({ headers: headers, method: 'get', params: myParams });
return this.http.get("this.url",options)
.map((res: Response) => res.json())
.catch(this.handleError);
}
Related videos on Youtube
mike
Updated on July 09, 2022Comments
-
mike almost 2 years
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.