角度> = 4.3,httpClient.get参数为空 [英] Angular >= 4.3, httpClient.get params empty
问题描述
我正在尝试将我的Http
请求迁移到HttpClient
请求.
我能够迁移post
查询,但是在迁移get
查询时遇到问题.这样做时,后端没有分别接收任何参数,它告诉我该参数未提供且为空.
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.
我做错了吗?
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);
});
}
有什么主意吗?
推荐答案
当前HttpParams
是不可变的,您应该将参数设置如下:
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 的set
和append
方法将用set
和append
用新更新的实例覆盖原始的params
实例,最后返回新实例.
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
重要提示:
自Angular v5.0.0起,您可以使用HttpParamOptions
中的fromObject
来同时添加多个参数.
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'}});
您还可以直接将object
参数设置为HttpClient
方法
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.
这篇关于角度> = 4.3,httpClient.get参数为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!