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

NgRx项目对接Mockoon报TypeError: entities is not iterable错误

报错原因

TypeError: entities is not iterable 是NgRx Entity的setAll方法接收到的第一个参数不是可迭代的数组导致的。
你对接json-server时运行正常,换Mockoon就报错,核心原因是两边接口返回结构不一致:

  • 你的Service中getBookmarks声明返回Bookmark[]类型,Effect拿到响应后直接把响应当成数组传给GetBookmarksSuccess的payload,最终在Reducer里传给bookmarkAdapter.setAll
  • 你配置的Mockoon接口返回的是带外层bookmarks键的对象,结构为{"bookmarks": [书签数组]},不是直接的数组。setAll接收到普通对象后无法迭代,直接抛出该错误。
修复方案

二选一即可:

  • 方案1:修改Mockoon接口配置,让GET /bookmarks接口直接返回书签数组,去掉外层包裹的{"bookmarks": ...}结构,和json-server的返回格式对齐。
  • 方案2:保留Mockoon现有返回格式,修改Service层代码,从响应中取出数组再返回:
    1. 从rxjs中导入map操作符
    2. 修改getBookmarks方法:
    import { map, Observable} from 'rxjs';
    
    // 类内方法
    getBookmarks():Observable<Bookmark[]>{
      return this.http.get<{bookmarks: Bookmark[]}>(this.apiURL)
        .pipe(map(res => res.bookmarks));
    }
    
其他隐藏问题修复

你的代码里还有两处会导致后续功能异常的问题,建议一并修复:

  1. Action类型拼写错误
    枚举BookmarkActionsTypes中的删除成功类型值拼写错误:'DELETE_BOOMARK_SUCCESS'多打了一个O,和DeleteBookmarksSuccess类中定义的type不匹配,会导致删除成功动作无法被Reducer正确识别。将枚举值修改为DELETE_BOOKMARK_SUCCESS = 'DELETE_BOOKMARK_SUCCESS'即可。
  2. Selector未绑定Feature State
    你当前的selectors没有把feature selector传给adapter的getSelectors方法,会导致选择器默认从全局State根级别查找NgRx Entity需要的ids、entities字段,无法正确取到数据。修改selector代码如下:
    export const getBookmarkState = createFeatureSelector<State>('angular');
    
    export const {
        selectAll: selectAllBookmarks,
    } = bookmarkAdapter.getSelectors(getBookmarkState);
    
    export const selectAll = createSelector(getBookmarkState, selectAllBookmarks);
    
    export const selectError = createSelector(getBookmarkState, (state:State):string=>state.error);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 00:09:22