angular - 如何在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
即外部观察者触发新内部流的发射的效果。但它需要是一种新的内在流,而不仅仅是原始流的重复。这可能吗?
解决方案
使用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
变体的运算符,例如map
and mapTo
...您通常想要普通的,To
变体是更特殊的情况。
推荐阅读
- java - 如何在 selenium 中使用 java 从 excel 工作表中检索 0.00000000 等十进制值?
- excel - VBA - 选择指定范围时在下一个单元格上调用函数
- vba - 需要建议或帮助来修改可以在通配符搜索 VBA 后搜索子字符串和格式的宏
- java - java spring bean factory可以返回bean列表吗?
- postgresql - PostgreSQL 安装错误,当位于 C:\Program Files (X86)\ 的 App 目录中时,带有“--”前缀
- html - 百分比和视口高度/宽度没有调整与格式化文本相关的比例
- python - 如何阻止第二个 PyQt5 QMainWindow 关闭?
- c# - 无法访问子页面中动态调用的用户控件中的控件
- reactjs - 三元运算符用 jest 测试用例
- javascript - JQUERY/HTML - 在下拉列表中选择值后显示/隐藏内容