javascript - 为什么观察不到可观察的
问题描述
我有两个级别的 observables,代码如下所示:
function level_1() {
...
level_2(params).subscribe((value) => {
if (value === something) {
action_1();
}
else { // others
action_2();
}
});
}
function level_2(params) : Observable<any> {
...
another_observable.subscribe((v) => {
if (a_condition) {
return of(something); // this is reached, but the observable is not captured
}
else {
return of (others);
}
});
return of(others); // this is captured
}
现在的问题是,在这三个“返回”中,level_1中只捕获了第三个,而level_2中达到了第一个,而level_1中没有捕获到第一个。我虽然 observable 会继续听,但我有什么遗漏吗?
解决方案
您可以从 中返回一个 observable level_2
,然后可以在 中订阅它level_1
:
function level_1() {
level_2().subscribe(value => {
if (value === 'something') {
console.log('action_1')
}
else {
console.log('action_2')
}
})
}
const another_observable = of(true) // This is just to make this example work
function level_2() {
return another_observable.pipe(
switchMap(value => {
if (value) {
return of('something')
}
else {
return of('others')
}
})
)
}
level_1()
...或者如果您只需要切换到一个值而不是另一个可观察的值,您可以使用map
而不是:switchMap
function level_2() {
return another_observable.pipe(
map(value => {
if (value) {
return 'something'
}
else {
return 'others'
}
})
)
}
推荐阅读
- typescript - 有没有办法在 Typescript 中制作对象的子集?
- python - Numpy 如何导入其 `numpy.core` 包?
- c - 在C中引用对齐的空结构?
- macos - 将私钥从证书导出到。Mac上的pem文件
- entity-framework-core - EFCore 3.1 FromSqlRaw 不工作并抛出一个奇怪的错误消息
- mysql - SQL查询的HQL查询
- flutter - Dart/Flutter - 为什么输出为空?
- amazon-web-services - terraform:有没有办法动态创建 iam 策略语句?
- python - 如何在完全不同的项目中从 .py 文件运行 .py 文件
- javascript - 按下子组件按钮时反应 Redux 如果 websocket 客户端在父级中,如何让 websocket 客户端发送数据?