An Angular tutorial — NgRx step-by-step

Carlos Caballero
Jul 18 · 4 min read

This post is part of a series in which I’m describing how to build your Pokédex using NgRx from beginner to ninja. If you want to read more, the links to the rest of the series are at the bottom of this article.


Introduction

It is essential to have read the first part of this post so you understand what we’re building. In this post, we will improve the code developed in the first post using the @ngrx/entity package, which will simplify the tasks of creating the reducers and selectors.


@ngrx/entity

The @ngrx/entity package is an adapter for managing record collections. This package provides an API to manipulate and query entity collections.

Therefore, it reduces boilerplate for creating reducers that manage a collection of models. It provides performant CRUD operations for managing entity collections. It is an extensible type-safe adapters for selecting entity information.

The first step is to install the package that will provide all these advantages.

npm i @ngrx/entity

EntityState

The EntityState is a predefined generic interface for a given entity collection with the following interface:

The reason we developed the PokemonState in the previous post with these two attributes is shown here. The generic attributes are the following:

  • ids. An array of all the primary IDs in the collection.
  • entities. A dictionary of entities in the collection indexed by the primary ID.

The pokemon.state.ts file is replaced by pokemon.adapter.ts as shown below.

Before:

After:

In our new model, we have created the alias PokemonState, based on EntityState using inheritance, although we haven’t included any new attribute to the state.

On the other hand, the createEntityAdapter method is responsible for creating the adapter for our Pokemon data model. This adapter is the one that provides us with a collection of methods to modify the state, as well as to create selectors.

The method takes an object with two properties for configuration:

  • selectId. A method for selecting the primary ID for the collection. Optional when the entity has a primary key of ID.
  • sortComparer. A comparing function used to sort the collection. The comparing function is only needed if the collection needs to be sorted before being displayed. Set it to false to leave the collection unsorted, which is more performant during CRUD operations.

In our case, we have not used any configuration property as it is not necessary.


Reducers

The returned adapter object provides a set of methods that you can use in your reducer function to manage the entity collection based on your provided actions.

  • getInitialState. Returns the initialState for an entity state based on the provided type. The initialState is provided to your reducer function. In our case, this function is wrapped inside of pokemonInitialState.

Adapter Collection Methods

The entity adapter also provides methods for operations against an entity. These methods can change one or many records at a time.

Each method returns the newly modified state, if changes were made, and the same state if no changes were made.

  • addOne: Add one entity to the collection.
  • addMany: Add multiple entities to the collection.
  • addAll: Replace the current collection with the provided collection.
  • removeOne: Remove one entity from the collection.
  • removeMany: Remove multiple entities from the collection, by ID or by predicate.
  • removeAll: Clear entity collection.
  • updateOne: Update one entity in the collection.
  • updateMany: Update multiple entities in the collection.
  • upsertOne: Add or update one entity in the collection.
  • upsertMany: Add or update multiple entities in the collection.
  • map: Update multiple entities in the collection by defining a map function, similar to Array.map.

This set of methods allows us to simplify our reduce function in which we had complex nested objects to modify properties.

In this way, note the before and after of this function, where the code has been reduced to invoke a method.

Before:

After:


Selectors

The getSelectors method, returned by the created entity adapter, provides functions for selecting information from the entity.

Therefore, the four most widely used selectors are:

Finally, the pokemon.selector.ts file is slightly modified because we do not need to build the selectAll selector as we will use the one provided by the adapter.

Before:

After:


Conclusion

In this post, we have refactored a small example of Pokédex using the @ngrx/entity package.

The use of an adapter will reduce unnecessary complexity in the management of the state of our application.

The adapter allows us to easily extend the state to our needs and has the most used operations when working with the state of an application.

Therefore, in this post we have covered the following topics:

  • Decouple management of the state of the visual components.
  • Create elements for management of the state efficiently and easily.
  • Create components that focus on relevance: the view.
  • Automate the creation of the state as it is very repetitive using @ngrx/entity.

The other posts in this series will cover interesting topics, such as:

  • Automating the creation of effects and actions, and simplifying the reduce function using @ngrx/entity.
  • Using a facade pattern through the @ngrx/data package.
  • Testing the application’s state.

It’s the concepts that are important, not the technique or library used. Therefore, this post should be taken as a guide for those who start large Angular applications and need to apply architectural principles.


Other Parts of the Series

  1. Part 1. Build your Pokédex: Introduction to NgRx
  2. Part 2. Build your Pokédex: @ngrx/entity
  3. Part 3. Build your Pokédex: Improve NgRx using create* functions (Coming soon)
  4. Part 4. Build your Pokédex: @ngrx/data (Coming soon)
  5. Part 5. Build your Pokédex: Testing NgRx (Coming soon)

Better Programming

Advice for programmers.

Carlos Caballero

Written by

Hi! My name is Carlos Caballero and I’m PhD. in Computer Science from Málaga, Spain. Teaching developers and degree/master computer science how to be experts!

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade