0

我有一个电话,我在其中获得了要提交的未完成报告的人员的 ID 列表,并且我想跟踪该人员未完成的报告的数量。我正在使用 EntityAdapter 存储该数据。现在我不知道如何在适配器中保持计数。

到目前为止,我已经检查了 ngrx 文档,尝试了很多对代码的操作,并在 gitter 聊天室问了我的问题,但到目前为止还没有结果。

我的服务返回一个字符串数组,其中包含人员的 id。示例数据可能是:

人员 ID 数组

在这里,我有两次相同的 ID,这意味着该人有 2 份报告。我想存储该 ID 并保持计数“2”。目前我正在将此代码用于适配器:

    export interface State extends EntityState<string> {
      showRegistrations: boolean,
      loading: boolean,
      loaded: boolean,
    }

    export const adapter: EntityAdapter<string> = createEntityAdapter<string>({
      selectId: (item: string) => item,
      sortComparer: false,
    });

    export const initialState: State = adapter.getInitialState({
      showRegistrations: true,
      loading: false,
      loaded: false,
    });

这在我的商店中为我提供了以下结果:

存储结果

但我实际上正在寻找以下结果,每个 Id 都存储在其中,并且我知道该 Id 被具体找到了多少次:

在此处输入图像描述

4

2 回答 2

0

@ngrx/entity旨在基于 id 存储和检索实体。您描述的用例不适合@ngrx/entity.

于 2019-10-02T17:07:06.293 回答
0

在跟进蒂姆的回答时,我查看了 ngrx/entity 的框外。我不应该一开始就专注于使用它,因为答案很简单。

我添加了一个包含字符串和数字的接口。在我的代码中,我称之为 ReportCount。然后在 loadsuccess 操作中,我要么添加一个带有用户 ID 的新 reportCount 并将 count 设置为 1,要么将 1 添加到 count。

最终,我得到了以下按预期工作的代码:

(我为可能陷入同一问题的其他人发布此信息)


export interface ReportCount{
  superintendent: string,
  count: number,
};


export interface State {
  reportCounts: ReportCount[],
  showRegistrations: boolean,
  loading: boolean,
  loaded: boolean,
};

export const initialState: State = {
  reportCounts: [],
  showRegistrations: true,
  loading: false,
  loaded: false,
};

export const reducer = createReducer(
  initialState,
  on(RegistrationActions.ShowRegistrations,
    (state, { setShow }) => ({
      ...state,
      showRegistrations: setShow,
    })
  ),

  on(RegistrationSuperintendentsCollectionActions.loadRegistrationSuperintendentCollection, (state) => ({
    ...state,
    loading: true,
  })),
  on(RegistrationSuperintendentsCollectionApiActions.loadRegistrationSuperintendentsSuccess,
    (state, { superintendents }) => {
      const repCount: ReportCount[] = [];
      superintendents.forEach(superintendent => {
        let sup = repCount.find(s => s.superintendent === superintendent);
        sup ? (sup.count = sup.count + 1) : repCount.push({superintendent, count:1});
      })
      return ({
        ...state,
        reportCounts: repCount,
        loading: false,
        loaded: true
      })
    }
  ),
);

export const getShowRegistrations = (state: State) => state.showRegistrations;

export const getLoaded = (state: State) => state.loaded;

export const getLoading = (state: State) => state.loading;

export const getLoadedSuperintendentRegistrations  = (state: State) => state.reportCounts; 
于 2019-10-03T18:15:34.947 回答