Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular >= 4.3, httpClient.get params empty

I'm trying to migrate my Http requests to HttpClient requests. I was able to migrate my post queries but I'm facing a problem while migrating get queries. When I do so, my backend doesn't receive any parameters respectively, it tells me that the parameters are not provided and empty.

Did I do something wrong?

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

constructor(private httpClient: HttpClient) {}

findItems() {
   let params: HttpParams = new HttpParams();
   params.set('something', 'hello');

   this.httpClient.get<any[]>('http://localhost:3000/apath/', {params})
    .subscribe((results: any[]) => {
      console.log(results);
    }, (errorResponse: any) => {
       console.error(errorResponse);
    });
}

Any idea?

like image 432
David Dal Busco Avatar asked Dec 02 '22 12:12

David Dal Busco


1 Answers

Currently HttpParams is immutable, you should set params as below:

// for set method
let params: HttpParams = new HttpParams().set('something', 'hello');
// for append method
let params: HttpParams = new HttpParams().append('something', 'hello');

HttpParams's set and append method will overwrite the original params instance with the newly updated one by set and append, and finally return the new instance.

So we can do it in multiple lines as below:

let params: HttpParams = new HttpParams();
params = params.set('something', 'hello');          
params = params.append('something2', 'hello2');

Plunker demo


Important:

Since Angular v5.0.0, you can use fromObject from HttpParamOptions to add multiple parameters at the same time.

const param = new HttpParams({fromObject: {aaa: '1', bbb: '222'}});

Also you can set object parameters to HttpClient methods directly

const obj = {aaa: '1', bbb: '222'};
this.http.get('test', { params: obj}).subscribe();

Refer demo, for the second way, please check browser's network to confirm the parameters has been added successfully.

like image 165
Pengyy Avatar answered Dec 23 '22 03:12

Pengyy