在这里,我想合并可观察值的值。 该代码有效,但是以这种方式进行嵌套订阅不是很好。 我正在寻找更好的解决方案。 预先感谢。
someObservable().subscribe(
data => { // array of elements
data.forEach(
element => {
anotherObservable(element.id)
.subscribe(
anotherData => doSomething(data, anotherData); // both data needed
);
}
);
}
);
答案 0 :(得分:2)
您可以使用 mergeMap
赞:
return this.someObservable().pipe(
mergeMap(element=> this.anotherObservable(element.id).pipe(
map(anotherData => {
return {
res1: element ,
res2: anotherData
}
})
))
)
答案 1 :(得分:1)
您可以使用合并
例如:-
// RxJS v6+
import { mapTo } from 'rxjs/operators';
import { interval, merge } from 'rxjs';
//emit every 2.5 seconds
const first = interval(2500);
//emit every 2 seconds
const second = interval(2000);
//emit every 1.5 seconds
const third = interval(1500);
//emit every 1 second
const fourth = interval(1000);
//emit outputs from one observable
const example = merge(
first.pipe(mapTo('FIRST!')),
second.pipe(mapTo('SECOND!')),
third.pipe(mapTo('THIRD')),
fourth.pipe(mapTo('FOURTH'))
);
//output: "FOURTH", "THIRD", "SECOND!", "FOURTH", "FIRST!", "THIRD", "FOURTH"
const subscribe = example.subscribe(val => console.log(val));