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

Ngrx Effect无法返回数据:API调用获取数据失败求助

NgRx API调用无法获取数据问题排查

核心问题分析与修复方案

1. Action类定义错误

你的Action类存在严重的类型匹配错误:

  • LoadItems类的type被错误赋值为ActionTypes.LoadSuccess,但它应该对应触发加载的ActionTypes.LoadItems
  • 类命名逻辑混乱,GetItems应该更名为LoadItems,原LoadItems需改为LoadSuccess以对应成功动作

修正后的Action代码:

import { Action } from '@ngrx/store';

interface Product {
    id : number;
    uid : string;
    blend_name: string;
    origin: string;
    notes: string;
    intensifier: string;
}

export enum ActionTypes {
    LoadItems = '[Products] Load items from server',
    LoadSuccess = '[Products] Load success'
}

export class LoadItems implements Action {
    readonly type = ActionTypes.LoadItems;
    // 触发加载的动作无需payload
}

export class LoadSuccess implements Action {
    readonly type = ActionTypes.LoadSuccess;
    constructor(public payload: Product[]) {}
}

export type ActionsUnion = LoadItems | LoadSuccess; 

2. Effect错误处理不规范

当前catchError直接返回错误对象,不符合NgRx Action格式,会导致Effect终止且错误无法被状态管理捕获。需改为返回标准错误Action:

catchError((error) => of({ type: '[Products] Load Failure', payload: error }))

3. 调试逻辑优化

你当前的console.log("here working")在Effect初始化时就会执行,无法验证LoadItems动作是否真的触发。调整调试位置到pipe内:

loadProducts$ = createEffect(() => { 
    return this.actions$.pipe(
        ofType(ActionTypes.LoadItems),
        tap(() => console.log("LoadItems动作已触发")),
        mergeMap(() =>
          this.productsService.getAll().pipe(
            tap(products => console.log("API返回数据:", products)),
            map(products => ({ type: ActionTypes.LoadSuccess, payload: products })),
            catchError((error) => of({ type: '[Products] Load Failure', payload: error }))
          )
        )
    )
});

4. API请求有效性验证

  • 打开浏览器开发者工具的Network面板,检查https://xxxxxxx请求的状态码与返回内容
  • 确认API返回的数据结构完全匹配Product接口定义

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:35:19