Angular >= 4.3, httpClient.get params empty

不想你离开。 提交于 2019-12-09 00:08:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/45500264/angular-4-3-httpclient-get-params-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!