繁体   English   中英

当 ngrx 实体为 id 返回未定义时如何解决问题

[英]how to fix issue when ngrx entity returned undefined for id

为什么会出现以下错误以及如何解决此问题。

传递给 selectId 实现的实体返回未定义。 您可能应该提供自己的 selectId 实现。 通过的实体:

可能您正在传递一个没有 id 属性的实体。 所以需要重写EntityAdapter创建中的selectId方法。

export const adapter: EntityAdapter<YourInterface> =
  createEntityAdapter<YourInterface>({
    selectId: nameofclass => nameofclass.yourID
  });

我通过在 EntityMetadataMap 中同时为多个实体指定元数据解决了这个问题:

// entity-store.module.ts

...

export function selectEventId(event: Event): number {
  return event.eventId;
}

export const entityMetadata: EntityMetadataMap = {
  User: {},
  Event: {
    selectId: selectEventId
  }
};

...

此错误通常与缺少 -实体主键有关:

每个实体类型都必须有一个主键,其值为整数或字符串。 NgRx 数据库假设实体有一个“id”属性,其值为主键。

并非每个实体都有一个名为“id”的主键属性。 对于某些实体,主键可以有任何名称,也可以是两个或多个属性的组合值。 在这些情况下,您始终使用以下函数指定该实体的主键:

选择Id

此函数返回该实体的指定字段/属性的主键值。

例如:

Entity Villain 没有名为“id”的主键,但名为“key”。 对于这个实体, selectId函数是这样的:

selectId: (villain: Villain) => villain.key;

实体元数据的完整声明可能类似于:

文件:../entity-store.module.ts

const entityMetadata: EntityMetadataMap = {

    ...

    Villain: {
                       // We MUST specify a primary key / id field for each entity
                       // (if it does not have its own prop/field named: 'id') !!!
        selectId: (villain: Villain) => villain.key, // <--- 

                       // optional setting - filter
        filterFn: filterForVillains,
                       // optional setting - sort order
        sortComparer: sortVillains
    },

    Hero { ... },

    ....

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM