作为this question的后续版,我已设法将多个过滤器应用于我的观察源,具体取决于用户决定应用哪些过滤器。
"问题"我不确定是否应用过滤器,即使这样,所有过滤器的工作方式也不同;一些是数字,另一些是字符串。
我得到了我的观察结果:
getProperties(): Observable<Property[]> {
return this.http.get<Property[]>(this.url);
}
并应用我的动态过滤器:
filterAndSort() {
let count = 0;
return this.getProperties()
//Only return properties where price is higher than or equal to min price
.map(properties => properties.filter((property) => {
if(property.price >= this.userSettings.getAppSetting("filterMinPrice", "number")) {
return property;
}
})
.filter((property) => {
//Return all properties if max price is not set (0)
if(this.userSettings.getAppSetting("filterMaxPrice", "number") == 0) {
return property;
}
//Only return properties where price is lower than or equal to max price
else if(property.price <= this.userSettings.getAppSetting("filterMaxPrice", "number")) {
return property;
}
})
.filter((property) => {
if(property.incomeCategory == this.userSettings.getAppSetting("filterIncomeClass", "string")) {
return property;
} else if (this.userSettings.getAppSetting("filterIncomeClass", "string") == "none") {
return property;
}
})
.filter((property) => {
if(property.numberOfRooms >= this.userSettings.getAppSetting("filterMinRooms", "number")) {
return property;
}
})
.filter((property) => {
if(property.numberOfBedrooms >= this.userSettings.getAppSetting("filterMinBedrooms", "number")) {
return property;
}
})
.sort((a: Property, b: Property) => {
//..
}
))
}
它有效,但我认为这不是最好的解决方案,因为我一遍又一遍地呼叫filter()
。我认为,如果我以某种方式设法减少过多的if条件并且只在这种条件下使用return property;
一次,那么我的代码将更加整洁。 (请记住,我将来会添加更多的过滤器选项,所以如果我必须以类似的方式应用它们,这肯定会变得更加混乱:p)
有什么建议吗?
(只是为了澄清事情:我在这里使用NativeScript / Angular / Typescript)。
答案 0 :(得分:2)
这可能有用我不确定它是否可以被认为是一种改进,只是试图将逻辑结果压缩成一个过滤函数:
.filter(property => {
if(
(
this.userSettings.getAppSetting("filterMaxPrice", "number") == 0 ||
property.price <= this.userSettings.getAppSetting("filterMaxPrice", "number")
) &&
(
property.incomeCategory == this.userSettings.getAppSetting("filterIncomeClass", "string") ||
this.userSettings.getAppSetting("filterIncomeClass", "string") == "none"
) &&
(
property.numberOfRooms >= this.userSettings.getAppSetting("filterMinRooms", "number")
) &&
(
property.numberOfBedrooms >= this.userSettings.getAppSetting("filterMinBedrooms", "number")
)
) {
return property;
}
})