问题描述
我遇到以下情况:
myObservable1.pipe(
switchMap((result1: MyObservable1) => {
if (condition) {
return myObservable2;
} else {
return of(null);
}
})
).subscribe(myObservable1 | myObservable2) => {
因此,如果条件为false,我只需要执行一个请求,如果条件为true,则必须将第一个请求链接到下一个请求,它们实质上是对服务器api的两个请求.
So if condition is false I only have to perform one request, if the condition is true, I have to chain the first request to the following one, they are essentially two requests to the server api.
是否有更好的解决方案而不返回该 null
?
RxJ中是否有条件运算符?
Is there a better solution without returning that null
?
Is there any conditional operator in RxJs?
谢谢!
推荐答案
另一种可能性是在SwitchMap中使用运算符iif.
Another possibility is to use the operator iif in a SwitchMap.
https://www.learnrxjs.io/learn-rxjs/operators/有条件的/iif
https://rxjs-dev.firebaseapp.com/api/index/函数/iif
但是它可以限制控制特定功能的可能性可观察条件:
but it can restrain the possibility to control specficconditions on your Observable :
myObservable1
.pipe(
switchMap(result1 =>
iif(() => condition
, myObservable2
, myObservable1
)
)
.subscribe(result => console.log(result));
您可以在其中用返回布尔值的函数替换"condition".具有功能:
Where you can replace 'condition' by a function returning a boolean.With a function :
myObservable1
.pipe(
switchMap(result1 =>
iif(() => test(result1)
, myObservable2
, myObservable1
)
)
.subscribe(result => console.log(result));
test(result1) : boolean {
if(result1){
// the iif() will return myObservable2
return true;
}else{
/: the iif() will return myObservable1
return false ;
}
}
就像@amjuhire说的那样,您可以使用过滤器和switchMap进行编写:
Like @amjuhire said , you can write with a filter and a switchMap :
myObservable1.pipe(
filter((result1) => condition)
switchMap((result1: MyObservable1) => {
return myObservable2;
})
).subscribe(result2 => { ... })
给出您的示例的另一种可能性:
Another possibility given your example :
myObservable1.pipe(
switchMap((result1: MyObservable1) => {
if (condition) {
return myObservable2;
} else {
return of(result1);
}
})
subscribe(result => console.log(result));
或在switchMap中使用EMPTY:
Or using EMPTY in the switchMap :
myObservable1.pipe(
switchMap((result1: MyObservable1) => {
if (condition) {
return myObservable2;
} else {
// Observable that immediately completes
return EMPTY;
}
})
subscribe(result2 => console.log(result2));
这里的问题是我们不知道您可观察的类型.
The problem here is that we don't know the type in your observable.
所以我无法断定哪种方式更好.
So i can't judge wich way is the better.
这还取决于您如何处理可观察对象的不同调用之间的成功/错误.
It also depends on how you want to handle the success/error between the different calls of your observable.
这篇关于基于条件的RXJS条件switchMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!