如何在HttpClient中"get"传递URLSearchParams.方法-角度5 [英] How to pass URLSearchParams in the HttpClient "get" method - Angular 5
问题描述
我将 Angular 4.2 与 Http 服务一起使用,并且我使用了类似get方法,其中params是URLSearchParams对象:
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})
我想迁移到 Angular 5 . http现在是 HttpClient 对象,就像角度小组推荐的那样. 我的搜索"键出错.
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.
在我的情况下,您知道如何将Http迁移到HttpClient服务吗?
Do you know how to migrate Http to HttpClient service in my case?
谢谢.
推荐答案
自Angular 4.3开始,您可以像这样使用HttpClient
:
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
和HttpHeaders
是不可变的类,因此在每次调用set
或append
方法后,它们都会返回一个新实例,这就是为什么您应该这样做:params = params.append(...)
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(...)
这篇关于如何在HttpClient中"get"传递URLSearchParams.方法-角度5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!