当我通过搜索栏传值调用搜索API时,如果没有值则会传一个”字段=“的值到后端,后端同事说尽量避免这样的情况,于是采用了下面的方法:
思路为在调用API之前逐步判断每个字段是否有值,如果没有值则不查询该字段
代码如下:
let strSearchOptions: string;
strSearchOptions = '';
if (this.orderId.value !== null && trim(this.orderId.value) !== '') {
strSearchOptions += '&id=' + trim(this.orderId.value);
}
……
if (this.fromDate.value !== null || this.toDate.value !== null) {
strSearchOptions += '&date_type=' + this.dateType.value;
if (this.fromDate.value !== null) {
strSearchOptions += '&createdTime_st=' + this.general.formatTimeToDate(this.fromDate.value);
}
if (this.toDate.value !== null) {
strSearchOptions += '&createdTime_et=' + this.general.formatTimeToDate(this.toDate.value);
}
}
const url = `planOrder/list?page=${this.paginator.pageIndex + 1}${strSearchOptions}`;
this.confSvc.sendGetCatch(url, this.isLoading).subscribe(res => {
this.tableData = res['data'].data || [];
this.resultsLength = res['data'].count;
this.confSvc.changeLoading(false);
});
其中strSearchOptions字段为所有非空字段的集合。
代码重构和优化
后来我发现每个具有搜索功能的页面均要进行判断,在开始下一个模块的编写后我编写了一个公用函数重构代码
组装get请求的字符串公用函数:
/**
* 组装get请求的params字符串
* @param params
*/
makeGetParamsStr(params: {key: string, value: string | number}[]): string {
let searchParamsStr = '';
params.forEach((item, index, array) => {
if (isNotNullOrUndefined(item.value)) {
searchParamsStr += '&' + item.key + '=' + item.value;
}
});
return searchParamsStr;
}
在组件中调用API:
const getParams: { key: string, value: string | number }[] = [
{ key: 'order_status', value: this.searchForm.value.orderStatus },
{ key: 'plan_type', value: this.searchForm.value.planType },
{ key: 'order_id', value: this.searchForm.value.orderId },
{ key: 'products_name', value: this.searchForm.value.productName},
{ key: 'suppliers_id', value: this.searchForm.value.supplierId },
{ key: 'spu', value: this.searchForm.value.spu },
{ key: 'buyer_id', value: this.searchForm.value.buyerId}
];
const searchParamsStr = this.confSvc.makeGetParamsStr(getParams);
this.purchaseService.getPurchaseOrderList(this.paginator.pageIndex, searchParamsStr).subscribe(
res => {
console.log(res);
this.tableData = res['data'].data || [];
this.tableDataLength = res['data'].count;
},
e => console.log(e),
() => this.isLoading = false
);
其中getParams为makeGetParamsStr函数所需要的数组结构。
searchParamsStr其实类似于最开始的strSearchOptions字符串,只不过这样避免了重复写法,以及占用大量篇幅的代码。