Angular 5多个逗号分隔的HttpParams

时间:2018-03-26 08:12:49

标签: angular angular5

我有一组数据,用户可以按状态过滤数据。状态已提交,未提交,已完成且已失败。

要过滤数据,我会向后端api发送get请求,看起来像这样。

/api/data/?status=uncommited,commmitted

上述调用只会返回未提交或已提交的数据。

我无法实现此功能,因为网络标签显示了我的请求,如下所示:

/api/data/?status=uncommited&status=commmitted

你能看到上面有两个“状态”而不是1是逗号分隔。

data.service.ts

get(params = null) {

    let endpoint = "<removed>/api/v1/jobs"

    let filters = new HttpParams({fromObject: params});

    return this.apiService.get(endpoint, filters);

}

data.component.ts

this.filterForm = this.fb.group({
            status: [],

        });

       this.filterForm.valueChanges.subscribe((res) => {

            this.filters = _.pickBy(res, _.identity);

            let params = this.filters;

            this.dataService.get(params).subscribe((res) => {
                this.dataSource = res.data;
            });
        });

data.component.html

form fxLayout="row" [formGroup]="filterForm" fxLayoutAlign="space-between center" fxLayoutGap="10px" (change)="filter()">

            <mat-form-field>
                <mat-select placeholder="Status" formControlName="status" multiple>
                    <mat-option value="any">Any</mat-option>
                    <mat-option value="completed">Completed</mat-option>
                    <mat-option value="uncommitted">Uncommited</mat-option>
                    <mat-option value="committed">Commited</mat-option>

                    <mat-option value="failed">Failed</mat-option>

                </mat-select>
            </mat-form-field>

1 个答案:

答案 0 :(得分:1)

您应该使用%2C来分隔status参数上传递的多个值。然后是服务器端执行URL解码以获取参数列表。 %2C,

的网址编码值

使用这种方法,Angular会将其视为单个参数,您的调用将是: /api/data/?status=uncommited%2Ccommmitted

<强>被修改

let status = ['uncommited', 'commmitted']
let filters = new HttpParams();
filters = filters.append('status', status.join(', ');
// Append here as much params as needed
this.apiService.get(endpoint, { params: filters });