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

Angular使用forkJoin处理嵌套HTTP请求时报期望流却传入undefined错误

你遇到的报错 Error: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. 核心原因是 result.map 回调的else分支没有返回值,导致传入forkJoin的数组中存在undefined元素,而forkJoin要求所有输入都必须是Observable、Promise等可迭代的流类型,遇到undefined就会抛出对应错误。

修复方案

只需要在else分支的this.client.get调用前添加return语句,把HTTP请求返回的Observable传递给map的返回值即可,修复后的完整代码如下:

test2(): Observable<Student[]> {
  return this.test1().pipe(
    mergeMap((result) => {
      if (!result) {
        return of(result);
      }
      return forkJoin(
        result.map((rr) => {
          if (rr.age === 1) {
            rr.age = rr.age * 10;
            return of(rr);
          } else {
            // 新增return语句,返回HTTP请求对应的Observable
            return this.client
              .get('https://api.coindesk.com/v1/bpi/currentprice.json')
              .pipe(
                map((res) => {
                  console.log(res);
                  rr.age = rr.age * 10000;
                  return rr;
                })
              );
          }
        })
      ).pipe(
        map((paths) => {
          console.log('w');
          console.log(paths);
          return paths;
        })
      );
    })
  );
}

可选优化

当前代码逻辑会直接修改原数组中的rr对象,如果需要避免修改原始数据产生副作用,可以在返回时生成新的对象:

// 替换上述代码中pipe内的map逻辑即可
map((res) => {
  console.log(res);
  return {
    ...rr,
    age: rr.age * 10000
  };
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:27:02