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

如何解决Angular报错:预期流却得到undefined,可提供Observable/Promise等类型

错误根因

你遇到的报错是由倒数第二个mergeMap操作符的错误用法导致的:mergeMap要求回调函数必须返回Observable、Promise、数组或可迭代对象这类流结构,但你在回调里调用了Array.forEach方法,该方法的返回值固定为undefined,刚好匹配报错提示里的「期望传入流却得到undefined」的问题,和你是否添加toArray操作符无关。

修复方案

你当前的逻辑只是遍历数组拼接字符串,属于不需要返回流的副作用操作,直接把对应的mergeMap替换为专门处理副作用的tap操作符即可,修改后代码如下:

IdSelection() {
  if (this.selection.selected.length > 0) {
    this.showProcessingFlag = true;
    this.dataToBeSent = ''; // 建议先初始化变量,避免多次调用时拼接旧数据
    from(this.selection.selected)
      .pipe(
        map((element) => element.Id),
        mergeMap((element) =>
          this.TaskService.getDetails(element, 0, '%27%27')
        ),
        filter((res) => res['commentId'] != null),
        mergeMap((res) => from(res['commentId'])),
        mergeMap((data) =>
          this.TaskService.getCmntDetails(0, Number(data), '%27%27')
        ),
        // 这里把mergeMap换成tap
        tap((innerRes) => 
          innerRes['commentRevId'].forEach(element => {
            this.dataToBeSent += element + '/' + innerRes['origReviewerId'] + ',';
          })
        ),
        toArray()
      )
      .subscribe((res) => {
        setTimeout(() => {   
          console.log(res);
          this.showProcessingFlag = false;
          // 如果需要去掉末尾的逗号可以在这里处理:this.dataToBeSent = this.dataToBeSent.slice(0, -1)
        }, 10);
      });
  }
}
补充说明

如果你后续需要对commentRevId里的每个元素做后续流处理,才需要用mergeMap返回from(innerRes['commentRevId'])结构,当前仅做数据拼接的场景下tap是最优选择。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:06:05