首页 > 解决方案 > 当在后端定义相关id时,如何为实体适配器定义selectId?

问题描述

我正在我的商店中调度 upsert 操作/reducer 以向状态添加新记录,并且有一个效果会调用后端并将记录/文档添加到我的 mongodb 实例。

鉴于此特定模型的唯一合理 id 是在创建文档时由我的后端逻辑定义的,我应该如何在前端的实体实现中定义 selectId?

目前,一个项目被添加到状态,id: undefined我收到警告:

entity.js:76 @ngrx/entity:传递给selectId 实现的实体返回未定义。您可能应该提供自己的selectId实现。

我的适配器定义为:

export const adapter: EntityAdapter<PublishedData> = createEntityAdapter<
  PublishedData
>({ selectId: (publishedData: PublishedData) => publishedData.doi });

相关的效果是:

@Effect()
  UpsertPublishedData$ = this.actions$.pipe(
    ofType<UpsertPublishedData>(PublishedDataActionTypes.UpsertPublishedData),
    switchMap(action => this.publishedDataApi.create(action.payload.publishedData)
    .pipe(mergeMap((data: PublishedData) => [ new UpsertPublishedData({ publishedData: data }),
      this.publishedDataApi.register(data[0].doi)]),
    catchError(err => of(new FailedPublishedDataAction(err)))))
  );

publishedData.doi是我需要用来引用实体的违规字段。

标签: angularapingrxngrx-entity

解决方案


现在我已经修改了reducer,使其不在id字段(doi)未定义的第一次传递中添加记录。

case PublishedDataActionTypes.UpsertWaitPublishedData: {
  if (action.payload.publishedData && action.payload.publishedData.doi) {
    return adapter.upsertOne(action.payload.publishedData, state);
  }
  return state;
}

从这个最初:

  case PublishedDataActionTypes.UpsertPublishedData: {
      return adapter.upsertOne(action.payload.publishedData, state);
    }

这确保状态中的记录与数据库中的记录匹配。这种方法仍然与不需要额外UpsertPublishedDataSuccess行动的实体方法一致。


推荐阅读