我目前正在使用带有功能测试的 API。所以我知道我会通过以下网址得到很好的回应:
/api/v1/investisseurs?vehicule%5B0%5D=4
解码后的等效 URL
/api/v1/investisseurs?vehicule[0]=4
使用 Angular 通过 HttpParams
发出我的调用,如下所示
getInvestors(params: HttpParams): Promise<MelodiiaCollectionResponse> {
console.log(params);
return <Promise<MelodiiaCollectionResponse>>this.http.get(environment.httpdBackHost + '/investisseurs', {
params: params,
}).toPromise();
在我的浏览器中出现以下请求的结果
/api/v1/investisseurs?vehicule%5B%5D=%5B%222%22%5D&page=1&max_per_page=15
解码后的等效 URL
/api/v1/investisseurs?vehicule[]=["2"]&page=1&max_per_page=15
问题,如何在 Angular 7 中拥有与 php 方法 http_build_query
相同的查询参数编码?
我想避免自己重新实现轮子:)
提前感谢您的帮助
最佳答案
您可以使用HttpParams
构建器通过链接append方法自动解析您的参数。通过一些 reducer ,您可以在 httpParams 中提供数组值
import { HttpParams } from '@angular/common/http';
//Whatever...
getInvestors(vehicules: number[], page: number, maxPerPage: number): Promise<MelodiiaCollectionResponse> {
const params = vehicules.reduce(
(previous, vehicule, index) => previous.append(`vehicule[${index}]`, vehicule.toString()),
new HttpParams()
)
.append('max_per_page', maxPerPage.toString())
.append('page', page.toString())
return this.http.get<MelodiiaCollectionResponse>(`${environment.httpdBackHost}/investisseurs`, {
params,
}).toPromise();
}
关于php - Angular 查询参数,如 httpd_query_params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649264/