Search code examples
angularngrxangular-ngrx-data

Ngrx-data select a single entity


I am using ngrx-data plugin (runs on top of ngrx), and I'm trying to select a single entity from the store (that ngrx data calls 'Cache'). I found that you can add a single entity to the cache but I can't find the way to retrieve a single item (based on Id) from the store.

Do I have to write my own selector for this? I would assume a simple operation like this would be provided by ngrx-data


Solution

  • I am sure there is a more elegant way to do this, but I was able to get a single entity by using the collection$ property on the data service.

    for example, I have an entity called Core and an EntityService called CoreEntityService. My entity cache has been populated through the coreEntityService.getByKey(id). Or I could have populated the entity cache by a getAll().

    when I want to retrieve the core with that id I use this construct, illustrated here by logging the single entity to the console:

    this.coreEntityService.collection$.subscribe(collection => console.log(collection.entities[id]))

    Edited to Add:

    you can also subscribe to entity service's entityMap$. I added a method to my entity service called selectEntityById like this which works well and returns an observable, unlike the previous code, which returns an actual object:

    selectEntityById(coreId: number): Observable<Core> {
    return this.entityMap$.pipe(
      map(entities => entities[coreId]),
      first());
    }
    

    The documentation for ngrx/data is not great at the moment but it is improving. I'm hoping that someone will post a better answer to this question soon.