如何在HttpClient中的查询字符串中传递数组?

时间:2017-11-10 07:46:05

标签: angular parameters

这是我的演员阵容:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.nishant.veuz.FragmentMainList">

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/main_progress_bar"
        android:layout_gravity="center"
        android:visibility="gone"/>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_view_main"
        android:dividerHeight="16dp"
        android:divider="@null"/>

</FrameLayout>

如何在HttpClient中的查询字符串中传递此数组?

我试图使用:

1)

['Elvis', 'Jane', 'Frances']

2)

let params = new HttpParams();
params = Params.append('actors[]', ['Elvis', 'Jane', 'Frances']);
this.http.get(url, { params: Params });

3)

let params = new HttpParams().set('actors[]', ['Elvis', 'Jane', 'Frances']);
this.http.get(url, { params: Params });

1和2不起作用,因为打字稿给出:

  

[ts]类型&#39;字符串[]&#39;的参数不能分配给&#39; string&#39;。

类型的参数

3只发送一个项目&#39;演员[]&#39;:&#39; Frances&#39;

12 个答案:

答案 0 :(得分:14)

我认为最好的方法是将它们作为string添加到参数中,并让后端将其转换回arraylist

let actorList = ['Elvis', 'Jane', 'Frances']
let params = new HttpParams();
params = params.append('actors', actorList.join(', ');
this.http.get(url, { params: Params });

答案 1 :(得分:4)

根据the interface,您可以这样做

const params = new HttpParams({ 
   fromObject: { 'actors[]': ['Elvis', 'Jane', 'Frances'] } 
});
this.http.get(url, { params });

答案 2 :(得分:3)

我使用URLSearchParams代替HttpParams。

使用URLSearchParams,您需要对数组进行字符串化,以将其设置为Params&#34; Key-Value-Store&#34;。

import { URLSearchParams } from '@angular/http';


let params: URLSearchParams = new URLSearchParams();
params.set('actors', JSON.stringify(yourArrayHere));

我认为这应该与HttpParams以相同的方式工作,因为它们都在set方法中使用Key-Value映射,所以试一试。

我希望这可以帮到你。

<强>更新

let options = new RequestOptions({search: params});

this._http.get(url, options).map(...)

使用RequestOptions您还可以编辑标题和其他请求选项。

答案 3 :(得分:3)

在Angular 6.0.6上工作:

private getParams(query) {
let params: HttpParams = new HttpParams();
for (const key of Object.keys(query)) {
  if (query[key]) {
    if (query[key] instanceof Array) {
      query[key].forEach((item) => {
        params = params.append(`${key.toString()}[]`, item);
      });
    } else {
      params = params.append(key.toString(), query[key]);
    }
  }
}
return params;

}

结果:

/api/message?page=1&per=2&order_by=name&order_direction=asc&base_object%5B%5D=2&base_object%5B%5D=1

答案 4 :(得分:2)

const actors = ['Elvis', 'Jane', 'Frances'];
let params = new HttpParams();
for (const actor of actors) {
  params = params.append('actors', actor);
}

this.http.get(url, { params: params }); 

答案 5 :(得分:2)

您可以使用JSON.stringify()来简单地做到这一点

    let params = new HttpParams();
    const actors = ['Elvis', 'Jane', 'Frances'];
    params.append('actors', JSON.stringify(actors);
    this.http.get(url, { params: params });

答案 6 :(得分:1)

这对我有用。

let params = new HttpParams();

['Elvis', 'Jane', 'Frances'].forEach((actorName:string) =>{
  params = params.append(`actors[]`, actorName);
})

OR

let params = new HttpParams();
let actorsArray:Array<string> = ['Elvis', 'Jane', 'Frances'];

actorsArray.forEach((actorName:string) =>{
  params = params.append(`actors[]`, actorName);
})

答案 7 :(得分:0)

let actorsArray = ['Elvis', 'Jane', 'Frances'];
this.http.get(url, { params: { actors: actorsArray } });

答案 8 :(得分:0)

这是一种简单的方法:

this.http.get(url, { 
    params: ['Elvis', 'Jane', 'Frances'].reduce((accumulator, name) => accumulator.append('names', name), new HttpParams())
});

答案 9 :(得分:0)

您可以执行以下操作:

this.http.get(url, { params: { "actors[]": actorsArray } });

答案 10 :(得分:0)

我使用了这种方法,并且在Angular 10中对我有用:

private paramMaker(data) : HttpParams
{
    let httpParams = new HttpParams();
    Object.keys(data).forEach((key) = > {
        if (Array.isArray(data[key]))
        {
            data[key].forEach((item, index) = > {
                httpParams = httpParams.append(key + '[' + index + ']', item);
            });
        }
        else
        {
            httpParams = httpParams.append(key, data[key]);
        }
    });
    return httpParams;
}

答案 11 :(得分:0)

添加这个以防有人遇到它。我能够覆盖默认行为,但只能通过覆盖 HttpParams 类并利用拦截器。它将数组值的参数名称更改为附加预期的 '[]'

class ArrayHttpParams extends HttpParams {
    constructor(options?: any) {
        if (options.cloneParams) {
            const {encoder} : {encoder: HttpUrlEncodingCodec} = options.cloneParams;
            options.encoder = encoder;
        }
        super(options);
        if (options.cloneParams) {
            const {updates, cloneFrom, map} : {updates: any[], cloneFrom: any, map: Map<string, string>} = options.cloneParams;
            (<any>this).updates = updates;
            (<any>this).cloneFrom = cloneFrom || null;
            (<any>this).map = map;
        }
    }
    toString(): string {
        super.toString();
        const {encoder} : {encoder: HttpUrlEncodingCodec} = <any>this;

        return this.keys()
            .map(key => {
                const values = this.getAll(key);
                const encodedKey = encoder.encodeKey(key) + (values.length > 1 ? '[]' : '');

                return values.map(value => encodedKey + '=' + encoder.encodeValue(value)).join('&');
            })
            .filter(param => param !== '')
            .join('&');
    }
}

class MyInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let params = null;
        if (req.method === 'GET' && req.params) {
            params = new ArrayHttpParams({cloneParams: req.params});
        }
        req = req.clone({
            setHeaders: headers,
            params: params || req.params
        });

        return next.handle(req);
    }
}