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.
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:
Angular 4 Way:
Angular 5 Way:
Multiple Params:
Since Angular 4.3 you can use
HttpClient
like this :HttpParams
andHttpHeaders
are immutable classes so after each call ofset
orappend
methods they return a new instance that's why you should do this :params = params.append(...)
I had a situation when there were multiple parameters that needed to be passed to the api. The only thing that worked for me is when calling set() method in the same line chained together during HttpParams object intialization: