- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 RxJs 时一个非常常见的问题似乎是希望一个或多个 observables 的结果然后在后续的中使用它们。
例如在伪代码中(这不是故意的 rx 或有效的 js 语法)
var someResult = $observable-A; // wait to complete
var finalResult = $observable-B(someResult.aValueINeed);
$observable-A.subscribe(resultA => {
$observable-B(resultA.aValueINeed)
.subscribe(resultB => {
console.log('After everything completes: ', resultB);
}
}
I also need to be able to subscribe to this function inside my service, this is why going with the subscribe method above, won't work for me.
最佳答案
Snorre Danielsen nailed this problem and full credit for this solution goes to him. I'd recommend having a look at this.
$observable-A.pipe(
mergeMap(resultA => {
return combineLatest(
of(resultA),
$observable-B(resultA)
)
}),
map(([resultA, resultB]) => {
// you can do anything with both results here
// we can also subscribe to this any number of times because we are doing all the processing with
// pipes and not completing the observable
}
)
mergeMap
(或
flatMap
这是一个别名)将一个 observable 作为输入并投影它(就像一个常规的 map 函数)。这意味着我们可以使用它的结果作为
$observable-B
的输入。 .现在这非常适合您实际上只想返回第二个可观察结果。例如
$observable-A.pipe(
mergeMap(resultA => $observable-B(resultA)),
map((resultB) => {
// resultA doesn't exist here and we can only manipulate resultB
}
)
combineLatest
是这里的关键。它允许
mergeMap
基本上“等待”内部可观察对象(
$observable-B
)完成。
pipe
中向下一个 rxjs 操作符返回一个 observable。 ,这不是我们想要的(因为您希望处理
pipe
中的常规运算符函数)。
of()
重新创建函数
resultA
, 如
combineLatest
仅将 observables 作为输入和
resultA
在这种状态下是一个完整的 observable。
A hint: Take a look at the
map(([resultA, resultB])
. The reason we use this notation to refer to our variables instead of the standardmap(results)
. Is so we can directly reference them without usingresults[0]
forresultA
orresults[1]
forresultB
. Its just a lot easier to read this way.
I hope this helps people out as I have yet to find a complete SO answer which covers this case. Edits are very welcome as its complicated and I'm sure its not a perfect answer.
关于angular - RXJS 如何在另一个中使用一个 observable 的结果(然后将这两个结果一起处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62141648/
我是一名优秀的程序员,十分优秀!