在 Angular 11 中添加多个同名参数
Add multiple parameters with same name in Angular 11
我想要做的是添加多个具有相同名称的参数来请求 URL with Angular 11:
http://example.com/somepath?data=1&data=2&data=3
我试过的是:
private getParams(value: string): HttpParams {
const values = value.split("/");
const httpParams = new HttpParams();
values.forEach((item) => httpParams.set('value', item));
return httpParams;
}
然后我尝试发送它:
public getConfig(view: string): Observable<IFooBar[]> {
const params = this.getParams(view);
return this.http.get<IFooBar[]>(`$somePerson/someMethod`, { params });
}
但是 url 变成没有参数:
http://localhost:8000/api/somePerson/someMethod
如何发送同名参数?
原因已设置并追加 returns 一个新实例,因此请务必保持更新。基于 doc.
let params = new HttpParams().append('value', '1');
params = params.append('value', '2');
params = params.append('value', '3');
params = params.append('value', '4');
console.log(params.getAll('value'));
所以你应该这样写:
private getParams(value: string): HttpParams {
const values:string[] = value.split("/");
let httpParams:HttpParams = new HttpParams();
values.forEach((item) => {
httpParams = httpParams.append('value', item)
});
return httpParams;
}
在您的情况下,我可能会像这样在同一参数上传递更多值:
public getConfig(view: string): Observable<IFooBar[]> {
const params = [1, 2, 3, 4, 5, 6];
return this.http.get<IFooBar[]>('somePerson/someMethod', { params: { values: params.join(',') } });
}
并在您的服务器端点(使用 express 发布示例):
app.get('somePerson/someMethod', (req, res) => {
const values = req.query.values?.split(',');
/* Now you have your values as an array of values */
});
我想要做的是添加多个具有相同名称的参数来请求 URL with Angular 11:
http://example.com/somepath?data=1&data=2&data=3
我试过的是:
private getParams(value: string): HttpParams {
const values = value.split("/");
const httpParams = new HttpParams();
values.forEach((item) => httpParams.set('value', item));
return httpParams;
}
然后我尝试发送它:
public getConfig(view: string): Observable<IFooBar[]> {
const params = this.getParams(view);
return this.http.get<IFooBar[]>(`$somePerson/someMethod`, { params });
}
但是 url 变成没有参数:
http://localhost:8000/api/somePerson/someMethod
如何发送同名参数?
原因已设置并追加 returns 一个新实例,因此请务必保持更新。基于 doc.
let params = new HttpParams().append('value', '1');
params = params.append('value', '2');
params = params.append('value', '3');
params = params.append('value', '4');
console.log(params.getAll('value'));
所以你应该这样写:
private getParams(value: string): HttpParams {
const values:string[] = value.split("/");
let httpParams:HttpParams = new HttpParams();
values.forEach((item) => {
httpParams = httpParams.append('value', item)
});
return httpParams;
}
在您的情况下,我可能会像这样在同一参数上传递更多值:
public getConfig(view: string): Observable<IFooBar[]> {
const params = [1, 2, 3, 4, 5, 6];
return this.http.get<IFooBar[]>('somePerson/someMethod', { params: { values: params.join(',') } });
}
并在您的服务器端点(使用 express 发布示例):
app.get('somePerson/someMethod', (req, res) => {
const values = req.query.values?.split(',');
/* Now you have your values as an array of values */
});