[英]Angular Rxjs - Conditional operator
I have a function that has three parameters: an id that I need as parameters for invoking the addEvent service, and other two parameters, two arrays that contains a list of people to add or remove to the event that I'm creating.我有一个 function ,它具有三个参数:一个我需要作为用于调用 addEvent 服务的参数的 id 和其他两个参数,两个 arrays 包含要添加或删除到我正在创建的事件的人员列表。 I must check if these arrays are empty or not to invoking some services.
我必须检查这些 arrays 是否为空或不调用某些服务。 I write it, but I don't like really much:
我写了它,但我不太喜欢:
addEvent(id: number, newPeople: any[], peopleToRemove: any[]) {
this.eventService.addEvent(id).pipe( mergeMap(res => {
if(newPeople.length > 0 && peopleToRemove.length > 0) {
return forkJoin([this.eventService.addPeople(res.id, newPeople), this.eventService.removePeople(res.id, peopleToRemove)])
}
else if(newPeople.length > 0 && peopleToRemove.length === 0) {
return this.eventService.addPeople(res.id, newPeople)
}
else if(peopleToRemove.length > 0 && newPeople.length === 0) {
return this.eventService.removePeople(res.id, peopleToRemove)
})).subscribe(res => {
if(newPeople.length) {
//doing something
}
if(peopleToRemove.length) {
//doing something
}
})
}
Is there an rxjs operator for doing the conditional check in a better way?是否有 rxjs 运算符可以更好地进行条件检查?
iif is the only rxjs conditional that could help, but the main issue here is that it only allows for a true or false check. iif是唯一可以提供帮助的 rxjs 条件条件,但这里的主要问题是它只允许进行真假检查。 In your case there are more scenarios, so you'd need to chain them.
在您的情况下,还有更多场景,因此您需要将它们链接起来。
I think simple boolean logic like you have is fine, although you could simplify your code by removing && newPeople.length === 0
and && peopleToRemove.length === 0
from the else if
s.我认为像您拥有的简单 boolean 逻辑很好,尽管您可以通过从
else if
s 中删除&& newPeople.length === 0
和&& peopleToRemove.length === 0
来简化代码。 If the if(newPeople.length > 0 && peopleToRemove.length > 0)
check is false (reaching the else if
s), it's already guarantees one of the array is empty, so checking for the one with length > 0
is enough.如果
if(newPeople.length > 0 && peopleToRemove.length > 0)
检查为假(到达else if
s),它已经保证数组之一为空,因此检查length > 0
的数组就足够了。
if(newPeople.length > 0 && peopleToRemove.length > 0) {
return forkJoin([this.eventService.addPeople(res.id, newPeople), this.eventService.removePeople(res.id, peopleToRemove)])
}
//if newPeople isn't empty, then peopleToRemove is guaranteed to be empty
else if(newPeople.length > 0) {
return this.eventService.addPeople(res.id, newPeople)
}
//if peopleToRemove isn't empty, then newPeople is guaranteed to be empty
else if(peopleToRemove.length > 0) {
return this.eventService.removePeople(res.id, peopleToRemove)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.