如何在 switchMapTo 的内部观察器中使用外部观察器的结果?

How do I use the result of the outer observer in the inner observer of switchMapTo?

我正在使用 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 实际上并不是 return 从外部观察者到内部观察者的结果。据我所知,内部流只初始化一次,然后由外部观察者的每个新发射触发

.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 内部流,而不仅仅是原始流的重复。这可能吗?

使用 switchMap,而不是 switchMapTo...

this.category$ = this.categoryId$.pipe(
  switchMap((newCategoryId) => 
    // inner stream is reinitialized using result from outer stream
    this.categoriesQuery.selectEntity(newCategoryId)
  )
)

switchMapTo 本质上是 shorthand 的 switchMap 切换到不关心外部可观察对象的静态可观察对象,而不是依赖它的动态可观察对象,这就是 switchMap 的目的。

类似的逻辑适用于所有具有 To 变体的运算符,例如 mapmapTo ...您通常需要普通的,To 变体是更特殊的情况。