如何将可观察数据通过管道传输到可观察数组中,并将其与内部的另一个可观察数据进行映射?
考虑以下可观察$:
getItems$()
返回以下数据:
[
{item: 1, value: 'one'},
{item: 2, value: 'two'},
{item: 3, value: 'three'},
...
]
所以我的问题是如何将上述可观察量映射到一个新的可观察量,以便在其中映射并解开另一组可观察量。
预期结果:
[
{item: 1, value: 'one', prop: 'someValueMappedFromAnotherObservableMethod1'},
{item: 2, value: 'two', prop: 'someValueMappedFromAnotherObservableMethod2'},
{item: 3, value: 'three', prop: 'someValueMappedFromAnotherObservableMethod3'},
...
// here someValueMappedFromAnotherObservableMethod1 is the value that should be obtained as a result of flatMapping observable inside the ```items.map()``` fn.
]
这是我尝试过的。它不起作用。它不是在 items.map()
this.getItems$()
.pipe(
flatMap((items) =>
items.map((item) => ({...item, prop: this.anotherMethodReturningObservableBasedOnItemValue$(item.value))}),
),
)
.subscribe(console.log);
但是上面的并没有按预期工作。让我知道如何做到这一点/
我也尝试过这种方法:
this.getItems$()
.pipe(
flatMap((items) =>
merge(items.map((item) => this.anotherMethodReturningObservableBasedOnItemValue$(item.value))).pipe(
combineAll(),
),
),
)
.subscribe(console.log);
最佳答案
您可以通过以下方式实现您想要的:
this.getItems$()
.pipe(
mergeMap(items =>
from(items)
.pipe(
mergeMap(item =>
this.anotherMethodReturningObservableBasedOnItemValue$(item.value)
.pipe(
take(1), // toArray operator below requires all sources to complete
map(prop => ({ ...item, prop })) // Combine new prop with existing props
)
),
// Combine all items into single array
toArray()
)
)
)
.subscribe(console.log);
关于javascript - 如何将可观察数据通过管道传输到可观察数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66495124/