Answer the question
In order to leave comments, you need to log in
How to refactor such code?
I use the following function on the project to remove filter fields:
clearAllControl() {
if (this.tableParam.region_id) {
delete this.tableParam.region_id;
this.searchForm.get('regionName').patchValue(null);
}
if (this.tableParam.district_id) {
delete this.tableParam.district_id;
this.searchForm.get('districtName').patchValue(null);
}
if (this.tableParam.area_id) {
delete this.tableParam.area_id;
this.searchForm.get('areaName').patchValue(null);
}
if (this.tableParam.city_id) {
delete this.tableParam.city_id;
this.searchForm.get('cityName').patchValue(null);
}
if (this.tableParam.place_id) {
delete this.tableParam.place_id;
this.searchForm.get('cityName').patchValue(null);
}
if (this.tableParam.name) {
delete this.tableParam.name;
this.searchForm.get('streetName').patchValue(null);
}
this.generateAddressesTable(this.tableParam);
}
Answer the question
In order to leave comments, you need to log in
We turn the common part of similar pieces of code into a function, and what they differ in, we will pass to this function as parameters:
[
{ del: 'region_id', search: 'regionName' },
{ del: 'district_id', search: 'districtName' },
{ del: 'area_id', search: 'areaName' },
{ del: 'city_id', search: 'cityName' },
{ del: 'place_id', search: 'cityName' },
{ del: 'name', search: 'streetName' },
].forEach(n => {
if (this.tableParam[n.del]) {
delete this.tableParam[n.del];
this.searchForm.get(n.search).patchValue(null);
}
});
+++
const config = [
'region', 'district', 'area', 'city',
{id:'place_id', name:'cityName'}, {id:'name', name:'streetName'},
];
clearAllControl() {
config.forEach(x=>{
let id = x.id || (x + '_id');
let name = x.name || (x + 'Name');
if (this.tableParam[id]) {
delete this.tableParam[id];
this.searchForm.get(name).patchValue(null);
}
});
this.generateAddressesTable(this.tableParam);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question