(Angular) State/Store Made Easy on Nx Workspace(Part 1)

Supawan Compun
FLOWACCOUNT TECH BLOG
2 min readMay 23, 2022

Nx workspace uses State Management with NgRx

Ngrx is a library that helps state management in an angular app, but one of the great side effects of using Ngrx is it promotes moving logic out of your components and one of the common pitfalls we see is people are putting all of their logics in their components.

What is Ngrx?

Ngrx is store provided for Angular.

Ngrx = redux + angular + rxjs
Ngrx = redux + angular + rxjs

SHARI Principle is used as a rule for selecting data to add to the store, but not all components must have a state/store.

Share (shared state) is accessed by many components and services.
Hydrated (hydrated state) is persistent from storage when the app starts. Available (available state) needs to be available when re-entering routes. Retrieved (retrieved state) is retrieved with a side effect.
Impacted (impacted state) is impacted by actions from other sources

Let’s start generating store library!

This is the command for generating.

nx g @nrwl/angular:ngrx app — module=apps/<appname>/src/app/app.module.ts — root

Example for generating a store in the library:

nx g @nrwl/angular:ngrx peoples --module=libs/peoples/src/lib/peoples.module.ts --directory +state/peoples --no-interactive

The following files are created, or updated:

peoples.actions.ts is used to describe the actions to load data peoples , load data peoples success , load data peoples failure its value.

peoples.actions.ts

peoples.effects.ts are side-effects that may happen after an action on the store; it is mostly used for HTTP requests.

peoples.reducer.ts are used as an initial state or set state from each action.

peoples.selectors.ts are helper functions for optimizing this selection.

After you can use store:

// Subscribe to the store using the custom pipeable operator   this.store$.select(selectors.getAllPeoples).pipe(takeUntil(this.ngUnsubscribe)).subscribe(peoples=> { //all people })

Extensions:

Use this extension to see the state of the store.

References:

[1]: State Management with NgRx

[2]: What is NgRx ?

For more articles from FlowAccount Tech Blog, please visit https://medium.com/flowaccount-tech.

Open Positions jobs available on FlowAccount > https://flowaccount.com/en/jobs

--

--