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

串联两个API响应的NGRX Effect无法运行,请求排查

NGRX Effect 第二个switchMap报错解决方案

报错原因

第二个switchMap的回调函数仅在resArray有效且长度大于0时返回了API请求的Observable,但当条件不满足时没有返回任何值,导致类型推断为Observable<Content[]> | undefined,而switchMap要求回调必须返回ObservableInput类型(不能是undefined)。

修复方案

在switchMap的回调中,为不满足条件的分支返回一个合法的Observable(比如空数组的Observable或者EMPTY),确保无论什么情况都返回符合要求的类型。

修复后的完整代码

import { of } from 'rxjs'; // 需导入rxjs的of工具

getFinalResponse$ = createEffect(
  () =>
    this.actions.pipe(
      ofType<Action & { request: apiRequest }>(
        ActionTypes.GetDetails
      ),
      switchMap(({ request }) => {
        const payload: apiRequest = request;
        return this.apiServiceOne
          .getDetails(payload)
          .pipe(
            map((response) => {
              let resArray: PData[] = [];
              if (response.arrayOne && response.arrayOne.length > 0) {
                resArray = response.arrayOne.filter(
                  (options) => options.id === "TEST1234"
                );
              }
              return resArray;
            })
          )
          .pipe(
            switchMap((resArray: PData[]) => {
              if (resArray && resArray.length > 0) {
                const secondReq: any = {
                  type: ['idtype']
                };
                return this.apiServiceTwo
                  .getData(secondReq)
                  .pipe(
                    map((triggers) => {
                      let finalArray: Content[] = [];
                      if (triggers.arraytwo && triggers.arraytwo.length > 0) {
                        finalArray = triggers.arraytwo.filter(
                          (opts) => opts.info && opts.info.selected
                        );
                      }
                      return finalArray;
                    })
                  );
              } else {
                // 返回空数组Observable,保证类型合法
                return of([]);
              }
            })
          )
          .pipe(
            map((result) => loadedRes({ response: result })),
            catchError((error) => of(loadedError({ error })))
          );
      })
    )
);

额外优化建议

  • 替换any类型为具体接口,提升代码类型安全性
  • 可通过filter操作符提前过滤无效的resArray,简化逻辑:
    .pipe(
      map(...),
      // 提前过滤掉无效数组,后续switchMap无需再判断
      filter(resArray => resArray?.length > 0),
      switchMap(resArray => {
        const secondReq: any = { type: ['idtype'] };
        return this.apiServiceTwo.getData(secondReq).pipe(...);
      }),
      // 过滤后无数据时返回默认空数组
      defaultIfEmpty([])
    )
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:37:42