我对可观察对象和RxJ是新手,我想要调节返回。如果第一个选择器返回一个特定值,我想从第二个选择器返回一个观察值。但是如果第一个选择器没有返回那个特定值,我想返回false (而不是(False))。我已经走到这一步了,但这将返回一个可观察对象。它不应该是嵌套的。我该怎么做呢?下面是目前为止的代码:
const condition$: Observable<boolean> =
this.store.pipe(
select(this.firstSelector.get()),
map(item=> {
if (item !== X) {
return of(false)
} else {
return this.store.pipe(select(this.secondSelector.hasValue()))
}
})
)发布于 2020-11-17 16:21:09
你就快到了。您应该使用像switchMap这样的高阶映射操作符来返回一个可观察值。map用于转换和返回来自可观察对象的数据。
const condition$: Observable<boolean> = this.store.pipe(
select(this.firstSelector.get()),
switchMap(item =>
(item !== X)
? of(false)
: this.store.pipe(select(this.secondSelector.hasValue()));
)
)发布于 2020-11-17 16:34:29
因此,如果您想在代码片段中使用if-else结构,可以执行以下操作
const condition$: Observable<boolean> =
this.store.pipe(
select(this.firstSelector.get()),
switchMap(item=> {
if (item !== X) {
return of(false)
} else {
return this.store.pipe(select(this.secondSelector.hasValue()))
}
})
)
switchMap运算符将返回一个新的observable。
使用if-else的另一种方式是使用分区运算符
const condition$ = this.store.pipe(select(this.firstSelector.get()))
const [_differentItem$, _sameItems$] = partition(condition$, (item) => item !== X);
const differentItem$ = _differentItem$.pipe(mapTo(false))
const sameItem$ = _differentItem$.pipe(switchMap(() => this.store.pipe(select(this.secondSelector.hasValue()))
在第二个示例中,分区操作符将创建两个可观察对象,其中第一个(_differentItem$)将在条件求值为true时发出,第二个(_sameItems)将在条件求值为false时发出
在那之后,我创建了两个包含其余逻辑的管道链,在differentItem$ im的情况下,直接使用mapTo操作符,它会将通过它的所有值映射到false,对于第二个可观察的sameItem$,我说只要你的源发出(例如,流过item === X),就会返回指向secondSelector的新的可观察对象。
https://stackoverflow.com/questions/64871528
复制相似问题