首页 > 解决方案 > 如何在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实际上并没有将外部观察者的结果返回给内部观察者。据我所知,内部流只初始化一次,然后由外部观察者的每个新发射触发

.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即外部观察者触发新内部流的发射的效果。但它需要是一种的内在流,而不仅仅是原始流的重复。这可能吗?

标签: angularrxjsrxjs-observables

解决方案


使用switchMap,而不是switchMapTo...

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

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

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


推荐阅读