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

在pipe中使用flatMap处理继承Service重写all方法返回的嵌套数组

首先修正你现有代码的小问题:all方法定义的形参是arg1、arg2,但调用父类super.all时传的是未定义的limit、filter变量,会先出现参数传递错误,需要先修正参数对应关系。

flatMap内的处理逻辑非常简单,只需要遍历拿到的数组,取出每一项的data字段,再把所有数组合并为一维数组后用of包裹返回即可,两种实现方式如下:

flatMap((data: Array<{data: any[]}>) => {
  // 方式1:ES6+ 环境直接用 map + flat 摊平数组
  const result = data.map(item => item.data).flat();
  // 方式2:兼容旧运行环境可以用 reduce 合并数组
  // const result = data.reduce((acc, cur) => acc.concat(cur.data), []);
  return of(result);
})

优化建议

因为你只是对数据流中的数据做同步转换,不需要生成新的Observable流,更建议用map操作符替代flatMap,代码更简洁:

import { map } from 'rxjs/operators';

export class ChildService extends ParentService {
  constructor(http: HttpClient) {
    super(http, myService);
  }
  
  all(arg1, arg2) {
    return super.all(arg1, arg2).pipe(
      map((data: Array<{data: any[]}>) => data.map(item => item.data).flat())
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:54:05