问题描述
从Angular 4.3开始,他们引入了HttpClient而不是Http.在HttpClient
中,我不能将URLSearchParams
用作url查询参数.而不是URLSearchParams
我正在使用HttpParams
From Angular 4.3 they introduced HttpClient instead of Http. in HttpClient
I can't use URLSearchParams
for url query parameter . instead of URLSearchParams
I'm using HttpParams
这项工作
var params = new HttpParams().append('a', '1').append('b', '2');
但是为什么这不起作用
var params = new HttpParams();
params.append('a', '1');
params.append('b', '2');
推荐答案
新的HTTP客户端适用于不可变的请求对象及其所有组成部分,例如HttpParams
和HttpHeaders
.要了解原因,请参见为什么http请求及其所有组成部分(如HttpHeaders和HttpParams)都是不可变的,或阅读文章有关Angular中拦截器和HttpClient机制的内幕指南.
The new HTTP client works with immutable request object and all its consistuent parts like HttpParams
and HttpHeaders
. To understand why see Why is http request and all its constituent parts like HttpHeaders and HttpParams are immutable or read the article Insider’s guide into interceptors and HttpClient mechanics in Angular.
这就是为什么append
方法合并参数并在每次调用append
时返回合并的HttpParams
对象的新实例的原因:
That is why append
method merges the parameters and returns the new instance of the merged HttpParams
object on each call to append
:
/**
* Construct a new body with an appended value for the given parameter name.
*/
append(param: string, value: string): HttpParams {
return this.clone({param, value, op: 'a'});
}
private clone(update: Update): HttpParams {
const clone = new HttpParams({encoder: this.encoder}); <-------
clone.cloneFrom = this.cloneFrom || this;
clone.updates = (this.updates || []).concat([update]);
return clone; <--------
}
所以在这里:
var params = new HttpParams().append('a', '1').append('b', '2');
带有b
的append
参数更新带有a
参数的append
返回的对象.
the append
with b
parameter updates the object returned by the append
with a
parameter.
尽管采用这种方法
var params = new HttpParams();
params.append('a', '1');
params.append('b', '2');
append
始终会更新HttpParams
的初始状态,而所有中间append
操作都将被有效忽略.
the append
always updates initial state of the HttpParams
and all intermediary append
operations effectively ignored.
所以您必须使用以前的返回值:
So you have to use the previous returned value:
var params = new HttpParams();
params = params.append('a', '1');
params = params.append('b', '2');
或在fromObject
中使用快捷方式:
let searchParams = new HttpParams({
fromObject: {
query: query,
sort: sort,
order: order
}
});
const modified = req.clone({params: searchParams});
或直接在请求上使用setParams
方法:
Or use setParams
method on a request directly:
const modified = req.clone({setParams: {'query': query, 'sort': sort, 'order': order}});
此外,从5.1.x开始,您可以直接传递对象而不是HttpParams实例:
Also, since 5.1.x you can pass object directly instead of an instance of HttpParams:
const params = {
'a': '1',
'b': '2'
};
this.http.get('...', { params })
这篇关于为什么HttpParams在angular 4.3中不能在多行中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!