Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 800
mike Avatar asked Nov 29 '17 11:11

mike


3 Answers

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(...)

like image 175
El houcine bougarfaoui Avatar answered Nov 16 '22 12:11

El houcine bougarfaoui


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);
like image 9
Daniel Segura Pérez Avatar answered Nov 16 '22 11:11

Daniel Segura Pérez


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);
}
like image 1
Rahul Avatar answered Nov 16 '22 11:11

Rahul