【发布时间】:2020-09-10 18:27:43
【问题描述】:
我正在使用switchMapTo 创建一个由外部观察者触发的内部流。
我想做什么(但不能)
// a change in value of categoryId triggers the inner observer to reinitialize
this.category$ = this.categoryId$.pipe(
switchMapTo((newCategoryId) =>
// inner stream is reinitialized using result from outer stream
this.categoriesQuery.selectEntity(newCategoryId)
)
)
...因为这是 switchMapTo 的实际工作方式
.switchMapTo 实际上并没有将外部观察者的结果返回给内部观察者。据我所知,内部流只初始化一次,然后由外部观察者的每个新发射触发
.switchMapTo 的实际工作原理:
this.category$ = this.categoryId$.pipe(
switchMapTo(
this.categoriesQuery.selectEntity(newCategoryId) // <= where does newCategoryId come from now?
)
)
而内部观察者只初始化一次
不幸的是,这也不起作用:
this.category$ = this.categoryId$.pipe(
tap((newValue) => {
this.currentCategoryId = newValue
}),
switchMapTo(() =>{
this.categoriesQuery.selectEntity(this.currentCategoryId)
}
)
)
因为内部观察者只初始化一次(不是在外部观察者的每次发射中),所以this.currentCategoryId 的值在第一次评估时是硬编码的。
有没有可能做我想做的事?
我很困惑。我想要switchMapTo 的效果,即外部观察者触发新内部流的发射。但它需要是一个 new 内部流,而不仅仅是原始流的重复。这可能吗?
【问题讨论】:
标签: angular rxjs rxjs-observables