NgRx in AG04

Mario Mijić
Agency04
Published in
7 min readJul 8, 2019

--

NgRx logo

Looking back at the last few months, there hasn’t passed a working day that I didn’t work with NgRx. In the following post, I will write about how we are using NgRx in AG04. The goal of this post isn’t to find out what NgRx is, but rather to share our personal experience while using NgRx.

I’m part of team developing a business application using Angular 6. We can claim that our application performance has been greatly improved by using state management.

Angular logo

I’ll create a simple application and provide a link to my GitHub repository, so you can just clone and play with the code.

Architecture

NgRx architecture

This is a basic schema for NgRx flow in our architecture. We define state inside of every feature module. Every model in diagram (service, effect, reducer etc.) has its own task that it is responsible for. In most cases, everything starts in a smart component, where we are dispatching specific action.

Effect gets triggered by dispatching action, which is due to some effects that needs to be called before reducer. In 90% cases we are calling REST service from effects. Then we are using received data for dispatching new action to save new data to store.

With this new action, that is dispatched in reducer, we are saving new and previous state. When the state is saved in store, we can then subscribe to the property selector in the smart component. After that, we are passing that result to view component through input method.

Example

In these few short sentences I explained how NgRx works in our applications. Now I’ll setup a simple application. First, a project will be create with using Angular CLI:

ng new ngrx-example

Second step is installing NgRx library. Below is a command for installing library:

npm install @ngrx/core @ngrx/store @ngrx/effects @ngrx/store-devtools @ngrx/router-store --save

After installation, the NgRx ecosystem is ready to use. Next step is importing StoreModule and EffectsModule in AppModule.

app.module.ts

Before starting with developing, it’s recommended to setup a meta-reducer for logging every action. Next step is installing ngrx-store-freeze:

npm i --save-dev ngrx-store-freeze

When installation of ngrx-store-freeze is done, it’s necessary to create file app.reducer.ts. Also, it is mandatory to create a debugMetaReducer function that will log old state, action that is dispatched and new state.

app.reducer.ts

Meta-reducers

Developers can think of meta-reducers as hooks into the action->reducer pipeline. Meta-reducers allow developers to pre-process actions before normal reducers are invoked.

Application structure

In this simple application, one extra module will be created. That module will have store folder, service, smart component and view component. In store folder will be five files (clubs.actions.ts, clubs.effects.ts, clubs.reducer.ts, clubs.selector.ts and clubs.state.ts).

├── app
│ ├── app.component.scss
│ ├── app.component.html
│ ├── app.component.ts
│ ├── app.module.ts
│ ├── app.reducer.ts
│ ├── clubs
│ ├── clubs.component.ts
│ ├── clubs.module.ts
│ ├── clubs.service.ts
│ ├── index.ts
│ ├── components
│ │ └── table
│ │ ├── table.component.scss
│ | ├── table.component.html
│ | └── table.component.ts
│ └── store
│ ├── clubs.actions.ts
│ ├── clubs.effects.ts
│ ├── clubs.reducer.ts
│ ├── clubs.selector.ts
│ └── clubs.state.ts
├── assets
│ ├── dummy
│ │ └── clubs.json
│ └── img
│ ├── asc.png
│ └── desc.png
├── environments
│ ├── environment.prod.ts
│ └── environment.ts
├── browserslist
├── index.html
├── main.ts
├── polyfills.ts
├── styles.css
├── test.ts
├── tsconfig.app.json
├── tsconfig.spec.json
└── tslint.json

Setting store inside specific module

During creating store, it’s compulsory to create state. The main goal is to develop store in every module that is used. Also, it’s necessary to init module state name (clubs.state.ts) and afterwards import that in ClubsModule.

export const clubStateName = 'club-module';

In the view component there will be a table for displaying names of the clubs, short name, club code, name of stadium, capacity and coach. There will be a nice feature of sorting data per every column. Then, it’s recommended to init some enum that will have two types of sorting (ascending and descending). It will be possible to save name of column and type of sorting in the store.

clubs.state.ts

Actions

Actions are one of the main building blocks in NgRx. Actions express unique events that happen throughout your application. From user interaction with the page, external interaction through network requests, and direct interaction with device APIs, these and more events are described with actions.

There will be three types of action (request for clubs, respond for clubs and sorting). In action for response and sorting it is needed to define the type of payload. ActionType is used to define the type of action, so it can be referenced in effect and reducer.

clubs.actions.ts

Reducers

Reducers in NgRx are responsible for handling transitions from one state to the next state in your application. Reducer functions handle these transitions by determining which actions to handle based on the action’s type.

Reducer is triggered by dispatching an action that is going to be called. They connect everything in background anytime a new action is dispatched.

Within this application there are two actions that will update state. First action RESPOND_CLUBS get payload with the clubs from response and then update clubs in state. Second action SORT_CLUBS allows getting the type of sort (field and order).

First thing is to save new sort that is dispatched. After that, we need to copy array before sorting, because the array is frozen in strict mode.

Next step is to check type of sorting, then sorting array of clubs and at the end returning new state. At the end, it is mandatory to copy the old state if there are not changes in any other states. Finally, it’s necessary to set new changes in state. Also, it is needed to set default case in switch statement, where it is possible to return old state.

clubs.reducer.ts

Effects

Effects are an RxJS powered side effect model for Store. Effects use streams to provide new sources of actions to reduce state based on external interactions such as network requests, web socket messages and time-based events.

Before starting with effects, in 90% of cases it is necessary to have REST service, that will return some response from backend (in our case we have dummy data in JSON file and it will return list of clubs).

clubs.service.ts

Effect is triggered when specific action is dispatched. It is similar to what reducers are doing, but in 90% of cases effects is used to calling REST service. After the effect is done, it returns new action that is going to dispatch and change/save data in store.

clubs.effects.ts

Selector

Selectors are pure functions used for obtaining slices of store state. @ngrx/store provides a few helper functions for optimizing this selection. Selectors provide many features when selecting slices of state.

After all of the above is done (state, actions, reducer and effect), it’s obligatory to setup the selector. Selector is used to get specific data that is needed in specific view component. First step is to setup which state name is used. Second step is to export const with specific data that returns Observable with property type.

clubs.selector.ts

Smart and view component

Smart component is component where all actions are dispatched and where is possible to get all data from state using selectors. Input and output method is used to pass data or dispatch some function to/from view component. In OnInit method is allowed to dispatch actions that are needed. Also, it’s available to select properly selector for input method.

clubs.component.ts

In the smart component, the async pipe is used for automatically subscribe to Observable and then return a new emit value. In case when changes happen in the state, async pipe automatically makes proper changes in component. Also, when the component is destroyed, async pipe automatically unsubscribes to avoid memory leak.

View component takes care for displaying the data and triggering event. It is not aware of how the data is retrieved or how the state changes. View components are based on the value of their input properties, nothing else. In view component folder const is initialised with the names and values for each column in table. Data is sent from smart component through input method. Output method for sorting is emitting new value that needs to be dispatched.

table.component.ts
table.component.html
table.settings.ts

Conclusions

In this article I tried to explain how and in which way we use NgRx in AG04. NgRx is very powerful and stable library that is very useful in big enterprise applications. This is an example how you can setup architecture for your application. However, if you’re going to work with this type of approach, it’ll take a lot more code to type.

GitHub repo

--

--