[英]Angular 2 & RxJS: map an array using Rx Observable
I have an array of numbers like this: [1, 2, 3], and HTTP service that has function to load data object by number like this: 我有一个数字数组,像这样:[1、2、3]和HTTP服务,它具有按数字按如下方式加载数据对象的功能:
function get(id: number): Observable<object>
How to map my original array of numbers to array of objects preserving order of elements? 如何将我的原始数字数组映射到保留元素顺序的对象数组?
You can use concatMap
operator. 您可以使用concatMap
运算符。
const Observable = Rx.Observable;
function mockHttpRequest(i) {
return Observable.of(i).delay(500);
}
Observable.from([1, 2, 3])
.concatMap(i => mockHttpRequest(i))
.subscribe(data => console.log(data));
This simulates multiple HTTP requests where each one is delayed by 500ms. 这模拟了多个HTTP请求,每个HTTP请求被延迟500ms。 Operator concatMap()
guarantees that the Observables will becalled in order. 运算符concatMap()
保证Observable会按顺序调用。
See live demo: https://jsbin.com/subuxo/edit?js,console 观看现场演示: https : //jsbin.com/subuxo/edit?js,console
Thanks to @martin I found this solution: 感谢@martin我找到了这个解决方案:
const myPromise = val => new Promise(resolve => setTimeout(() => resolve(`Promise Resolved: ${val}`),
Math.round(Math.random() * 1000 + 1000)))
const queue = Rx.Observable.of([1,2,3,4,5]);
const result = queue
.mergeMap(q => Rx.Observable.forkJoin(...q.map(myPromise)));
const subscribeTwo = result.subscribe(val => console.log(val));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.