You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RxJS使用from操作符后合并处理后的结果为数组

你的现有代码的问题:
from([1,2,3,4,5]) 会依次独立发出1、2、3、4、5五个值,你当前使用的concatMap(el => of(el))属于冗余逻辑,只是把每个值重新封装为Observable后原样发出,所以subscribe回调会被触发5次,每次拿到单个元素,自然得不到完整数组。

想要拿到最终的合并数组,只需要在pipe的末尾加入toArray操作符即可,它会缓存上游所有发出的值,等到上游 Observable 完成(from遍历完数组所有元素后会自动触发完成信号)时,把所有缓存值组装为一个数组一次性发出。

调整后的代码如下:

import { from } from 'rxjs';
import { map, toArray } from 'rxjs/operators';

from([1,2,3,4,5]).pipe(
  map(item => item + 1),
  toArray()
).subscribe(res => console.log("res", res)) // 输出:res [2, 3, 4, 5, 6]

如果你的实际业务场景中确实需要保留concatMap逻辑(比如里面有其他异步处理操作),只需要在concatMap之后再加toArray即可:

import { from, of } from 'rxjs';
import { map, concatMap, toArray } from 'rxjs/operators';

from([1,2,3,4,5]).pipe(
  map(item => item + 1),
  concatMap(el => of(el)), // 可替换为你实际的业务逻辑
  toArray()
).subscribe(res => console.log("res", res))

内容的提问来源于stack exchange,提问作者Benjamin McFerren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 07:12:03