Ngrx-data select a single entity

ngrx data flow
ngrx/entity selectors
ngrx-data custom effect
ngrx data pagination
where does ngrx/store data
ngrx/store update data
ngrx selectors
ngrx 10

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

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.

NgRx, entity-data main module includes effects and HTTP data services Configure with See EntityDataService for services that target a single EntityCollection. register a single data service by entity name with the registerService () method. register several data services at the same time with by calling registerServices with an entity-name/service map. You can create and import a module that registers your custom data services as shown in the EntityDataService tests

I had the same question and arrived at a slightly different result. This is not necessarily any better than the other answer, but it does work in a slightly different manner.

Just as glitchbane said in his answer, the documentation is a work in progress so I am also hoping that I am missing some readily available method to do this provided by ngrx-data, but I have yet to find one.

I wanted my subscription to provide the single element I was looking for rather than using the id to select the element inside the subscription. This lead me to creating a selector.

Imports and Selector:

import { createSelector } from '@ngrx/store';
import { EntityCollection } from '@ngrx/data';
import { MyModel } from '....my.model';

export const selectMyModels =
    (entities: EntityCollection<MyModel>) => entities.entities;

export const selectMyModelById = (id: number) => createSelector(
    selectMyModels,
    entities => entities[id]
);

Example usage:

this.myModelEntityCollectionService.collection$.pipe(
    select(selectMyModelById(1)))                    // <-- used here
        .subscribe((myModel: MyModel) => {
            this.myLogger.log(JSON.stringify(myModel));
        }
);

EntityCollectionService, An EntityCollectionService is a facade over the NgRx Data dispatcher and Each observable watches for a specific change in the cached entity collection and emits the A selector$ property is an observable that emits when a selected state  Besides a single user we can select a list of users. For that we need rootEntities function from the library. export const selectUsers = rootEntities(selectUser, // simply pass here a select for a single entity.

We need somehow to use this

` constructor(private authDataService: AuthDataService, private authEntityService: AuthEntityService, private authEntitySelectorFactory: AuthEntitySelectorFactory)

const collectionSelectors = authEntitySelectorFactory.createCollectionSelector('auth');

collectionSelectors.projector ?? `

NgRx Entity - Complete Practical Guide, When using NgRx to build our application, one of the first things that we have to do is to decide what is the best possible format for storing data  The NgRx Data library extends Entity. The Entity library provides the core representation of a single entity collection within an NgRx Store. Its EntityAdapter defines common operations for querying and updating individual cached entity collections. The NgRx Data library leverages these capabilities while offering higher-level features including:

I start using Ngrx-data not along time ago...I supposed you can create selectors in other ways.

However, I will explain how I used to do for entities coming directly from our model, cache and so on ... What I am doing is importing the service in the constructor

  constructor(private myModelsService: myModelEntityService) { } 

And then for example getting all the entities with

ngOnInit(){
    this.entities$ = this.myModelsService.entities$;
}

Finally, to solve your problem that it is just to take a saved entity from your store or as is the same rescuing from the observable of entities; I would catch the entity up like below

this.myEntity$ = this.myModelsService.entities$.pipe(mergeAll(), take(n), last())

Basically, your are doing an emission for every entities with mergeAll (decomposing an array), cutting them with take and setting the "n" that you want (let's say you need the third element, then n="3") and completing the emissions with last so you just have this element.

I hope it helps you or may give you the right direction.

Selecting one entity by id with adapters · Issue #1156 · ngrx/platform , Unfortunately, I very often need to select just one entity by its id (that never changes). A naive implementation of this requirement would be: Entity State adapter for managing record collections. Entity provides an API to manipulate and query entity collections. Reduces boilerplate for creating reducers that manage a collection of models. Provides performant CRUD operations for managing entity collections. Extensible type-safe adapters for selecting entity information. Installationlink

Angular.Schule → NgRx Data Views: How to de-normalize entities , Most of the time, data for a single entity has to be retrieved with multiple Every component displaying books will have to select the normalized  But a Store MetaReducer neither see nor wrap an entity collection reducer. These entity collection reducers are internal to the EntityCache Reducer that is registered with the NgRx Data feature. An entity collection MetaReducer is narrowly focused on manipulation of a single, target entity collection. It wraps all entity collection reducers.

How to use @ngrx/data in 3 Steps - Nikhil Kapoor, No need to implement the service layer (Http one), it handles automatically… smart Nah? import { EntityDataModule } from '@ngrx/data'; NgRx is a framework for building reactive applications in Angular. NgRx provides state management, isolation of side effects, entity collection management, router bindings, code generation, and developer tools that enhance developers experience when building many different types of applications. Why NgRx for State Management?link

ngrx-entity-relationship, Selector of related entities for @ngrx/entity and @ngrx/data. selectUser, // simply pass here a select for a single entity. );. Now we can use the  Angular NgRx Entity - Complete Practical Guide Last Updated: 24 April 2020 local_offer NgRx When using NgRx to build our application, one of the first things that we have to do is to decide what is the best possible format for storing data inside the store.

Comments
  • This does not provide an answer to the question. You can search for similar questions, or refer to the related and linked questions on the right-hand side of the page to find an answer. If you have a related but different question, ask a new question, and include a link to this one to help provide context. See: Ask questions, get answers, no distractions