【问题标题】:How to get NGRX/Entity length in the reducer?如何在减速器中获得 NGRX/实体长度?
【发布时间】:2022-08-09 07:30:01
【问题描述】:

在一个客户项目中,我使用 NGRX/Store 和 NGRX/Entity。

虽然商店的大部分由实体组成,但我必须在状态中存储其他值。出于业务原因,我需要某个时间点的所有项目的长度。

export interface State extends EntityState<Item> {
  initialItemListSize: number; // this should hold the length of entity-adapters items-list-size at a certain point
}

无论如何,在某些时候我只想

this.store.dispactch(saveItemListSizeNow);

称呼。

现在我想知道我必须在哪里实现逻辑(获取列表长度)。

一开始我以为在减速机

on(Itemctions.saveItemListSizeNow, (state) => {
    const size = ... //<--- no Idea how to get the length here
    return { ...state, initialItemListSize: size };
  }),

有人可以给我答案吗?

    标签: angular ngrx ngrx-store ngrx-entity


    【解决方案1】:

    您可以访问状态上的实体。

    state.ids.length
    

    例如。:

    on(Itemctions.saveItemListSizeNow, (state) => {
        const size = ... //<--- no Idea how to get the length here
        return { ...state, initialItemListSize: state.ids.length};
      }),
    

    【讨论】:

      【解决方案2】:

      您的操作可以使用可以在调度它时传递的有效负载数据来定义,例如:

      import { createAction, props } from '@ngrx/store';
      
      export const saveItemListSizeNow= createAction(
        '[Action Source] Save Item list size',
        props<{ itemListSize: number }>()
      );
      

      当你发送它时,

      store.dispatch(saveItemListSizeNow({ itemListSize: givenSize }));
      

      你的减速器会是这样的

      on(Itemctions.saveItemListSizeNow, (state, action) => {
        const size = action.itemListSize;
        return { ...state, initialItemListSize: size };
      }),
      

      【讨论】:

        猜你喜欢
        • 2017-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多