Before We Get Started
This article is not intended to be a tutorial on NgRx. There are several great resources that currently exist, written by experts much smarter than me. I highly suggest that you take time and learn NgRx and the redux pattern before attempting to implement these concepts.
- Ultimate Angular — NgRx Store & Effects
- Pluralsight — Play by Play Angular NgRx
- NgRx Blog on Medium.com
- NgRx.io Docs
- NgRx.io Resources
Background
The following represents a pattern that I’ve developed at my day job after building several enterprise Angular applications using the NgRx library. I have found that most online tutorials do a great job of helping you to get your store up and running, but often fall short of illustrating best practices for clean separation of concerns between your store feature slices, root store, and user interface.
With the following pattern, your root application state, and each slice (property) of that root application state are separated into a RootStoreModule and per feature MyFeatureStoreModule.
Prerequisites
This article assumes that you are building an Angular v6 CLI generated application.
Installing NgRx Dependencies
Before we get started with generating code, let’s make sure to install the necessary NgRx node modules from a prompt:
npm install @ngrx/{store,store-devtools,entity,effects}
Best Practice #1 — The Root Store Module
Create a Root Store Module as a proper Angular NgModule’s that bundles together NgRx store logic. Feature store modules will be imported into the Root Store Module allowing for a single root store module to be imported into your application’s main App Module.
Suggested Implementation
- Generate RootStoreModule using the Angular CLI:
ng g module root-store —-flat false —-module app.module.ts
2. Generate RootState interface to represent the entire state of your application using the Angular CLI:
ng g interface root-store/root-state
This will create an interface named RootState
but you will need to rename it to State
inside the generated .ts
file as we want to, later on, utilize this as RootStoreState.State
PLEASE NOTE: You will come back later on and add to this interface each feature module as a property.
Best Practice #2 — Create Feature Store Module(s)
Create feature store modules as proper Angular NgModule’s that bundle together feature slices of your store, including state, actions, reducer, selectors, and effects. Feature modules are then imported into your RootStoreModule. This will keep your code cleanly organizing into sub-directories for each feature store. In addition, as illustrated later on in the article, public actions, selectors, and state are name-spaced and exported with feature store prefixes.
Naming Your Feature Store
In the example implementation below we will use the feature name MyFeature, however, this will be different for each feature you generate and should closely mirror the RootState property name. For example, if you are building a blog application, a feature name might be Post.
Entity Feature Modules or Standard Feature Modules?
Depending on the type of feature you are creating you may or may not benefit from implementing NgRx Entity. If your store feature slice will be dealing with an array of type then I suggest following the Entity Feature Module implementation below. If building a store feature slice that does not consist of a standard array of type, then I suggest following the Standard Feature Module implementation below.
Suggested Implementation — Entity Feature Module
- Generate MyFeatureStoreModule feature module using the Angular CLI:
ng g module root-store/my-feature-store --flat false --module root-store/root-store.module.ts
2. Actions — Create an actions.ts file in the app/root-store/my-feature-store directory:
3. State — Create a state.ts file in the app/root-store/my-feature-store directory:
4. Reducer — Create a reducer.ts file in the app/root-store/my-feature-store directory:
5. Selectors — Create a selectors.ts file in the app/root-store/my-feature-store directory:
6. Effects — Create an effects.ts file in the app/root-store/my-feature-store directory with the following:
Suggested Implementation — Standard Feature Module
- Generate MyFeatureStoreModule feature module using the Angular CLI:
ng g module root-store/my-feature-store --flat false --module root-store/root-store.module.ts
2. Actions — Create an actions.ts file in the app/root-store/my-feature-store directory:
3. State — Create a state.ts file in the app/root-store/my-feature-store directory:
4. Reducer — Create a reducer.ts file in the app/root-store/my-feature-store directory:
5. Selectors — Create a selectors.ts file in the app/root-store/my-feature-store directory:
6. Effects — Create an effects.ts file in the app/root-store/my-feature-store directory with the following:
Suggested Implementation — Entity and Standard Feature Modules
Now that we have created our feature module, either Entity or Standard typed above, we need to import the parts (state, actions, reducer, effects, selectors) into the Angular NgModule for the feature. In addition, we will create a barrel export in order to make imports in our application components clean and orderly, with asserted name-spaces.
- Update the app/root-store/my-feature-store/my-feature-store.module.ts with the following:
2. Create an app/root-store/my-feature-store/index.ts barrel export. You will notice that we import our store components and alias them before re-exporting them. This, in essence, is “name-spacing” our store components.
Best Practice #1 — The Root Store Module (cont.)
Now that we have built our feature modules, let’s pick up where we left off in best practice #1 and finish building out our RootStoreModule and RootState.
Suggested Implementation (cont.)
3. Update app/root-store/root-state.ts and add a property for each feature that we have created previously:
4. Update your app/root-store/root-store.module.ts by importing all feature modules, and importing the following NgRx modules: StoreModule.forRoot({}) and EffectsModule.forRoot([]):
5. Create an app/root-store/selectors.ts file. This will hold any root state level selectors, such as a Loading property, or even an aggregate Error property:
6. Create an app/root-store/index.ts barrel export for your store with the following:
Wiring up the Root Store Module to your Application
Now that we have built our Root Store Module, composed of Feature Store Modules, let’s add it to the main app.module.ts and show just how neat and clean the wiring up process is.
- Add RootStoreModule to your application’s NgModule.imports array. Make sure that when you import the module to pull from the barrel export:
import { RootStoreModule } from ‘./root-store’;
2. Here’s an example container component that is using the store:
Finished Application Structure
Once we have completed implementation of the above best practices our Angular application structure should look very similar to something like this:
├── app │ ├── app-routing.module.ts │ ├── app.component.css │ ├── app.component.html │ ├── app.component.ts │ ├── app.module.ts │ ├── components │ ├── containers │ │ └── my-feature │ │ ├── my-feature.component.css │ │ ├── my-feature.component.html │ │ └── my-feature.component.ts │ ├── models │ │ ├── index.ts │ │ └── my-model.ts │ │ └── user.ts │ ├── root-store │ │ ├── index.ts │ │ ├── root-store.module.ts │ │ ├── selectors.ts │ │ ├── state.ts │ │ └── my-feature-store │ │ | ├── actions.ts │ │ | ├── effects.ts │ │ | ├── index.ts │ │ | ├── reducer.ts │ │ | ├── selectors.ts │ │ | ├── state.ts │ │ | └── my-feature-store.module.ts │ │ └── my-other-feature-store │ │ ├── actions.ts │ │ ├── effects.ts │ │ ├── index.ts │ │ ├── reducer.ts │ │ ├── selectors.ts │ │ ├── state.ts │ │ └── my-other-feature-store.module.ts │ └── services │ └── data.service.ts ├── assets ├── browserslist ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── index.html ├── main.ts ├── polyfills.ts ├── styles.css ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── tslint.json
Fully Working Example — Chuck Norris Joke Generator
I have put together a fully working example of the above best practices. It’s a simple Chuck Norris Joke Generator that has uses @angular/material and the http://www.icndb.com/ api for data.
Github
wesleygrimes / angular-ngrx-chuck-norris
Chuck Norris Joke Generator w/ NgRx Store
Angular NgRx Chuck Norris Joke Generator
This project is a Chuck Norris Joke Generator backed by an NgRx Store using best practices as described in this article: Link to article
This project was generated with Angular CLI version 7.3.3.
Development server
Run ng serve
for a dev server. Navigate to http://localhost:4200/
. The app will automatically reload if you change any of the source files.
Code scaffolding
Run ng generate component component-name
to generate a new component. You can also use ng generate directive|pipe|service|class|guard|interface|enum|module
.
Build
Run ng build
to build the project. The build artifacts will be stored in the dist/
directory. Use the --prod
flag for a production build.
Running unit tests
Run ng test
to execute the unit tests via Karma.
Running end-to-end tests
Run ng e2e
to execute the end-to-end tests via Protractor.
Further help
To get more help on the Angular CLI use…
Stackblitz
You can see the live demo at https://angular-ngrx-chuck-norris.stackblitz.io and here is the Stackblitz editor:
angular-ngrx-chuck-norris - StackBlitz
_NgRx _Best_Practices_Chuck_Norris_Example_stackblitz.com
Conclusion
It’s important to remember that I have implemented these best practices in several “real world” applications. While I have found these best practices helpful, and maintainable, I do not believe they are an end-all-be-all solution to organizing NgRx projects; it’s just what has worked for me. I am curious as to what you all think? Please feel free to offer any suggestions, tips, or best practices you’ve learned when building enterprise Angular applications with NgRx and I will update the article to reflect as such. Happy Coding!
Additional Resources
I would highly recommend enrolling in the Ultimate Angular courses, especially the NgRx course. It is well worth the money and I have used it as a training tool for new Angular developers. Follow the link below to signup.
Ultimate Courses: Expert online courses in JavaScript, Angular, NGRX and TypeScript
_Expert online courses in JavaScript, Angular, NGRX and TypeScript. Join 50,000 others mastering new technologies with…_ultimatecourses.com
Top comments (14)
Hello,
I have two features in my store: Auth and Itsm. After a successful connection with Auth, I want to send the first action of Itsm. But there is a circular dependency.
I think I have built all the stores by following the tutorial. If I use the router directly in Auth-Effects, it works well.
Do you have an example with two features and one calling the second?
Thank you for this tutorial which is what I needed.
Daniel
Great Question Daniel! You should be able to dispatch actions in other features from effects. Is this not working?
Hi
I have built AuthStoreModule and ItsmStoreModule with the same plan - from tutorial.
They are both injected in RootStoreModule.
I get "WARNING in Circular dependency detected:" when in auth-store/effects I want to "this.store.dispatch(new ItsmStoreActions.ItsmBeginLoadingRequests())"
Complete error is
WARNING in Circular dependency detected:
src\app\root-store\root-store.module.ts -> src\app\root-store\auth-store\auth-store.module.ts -> src\app\root-store\auth-store\effects.ts -> src\app\root-store\index.ts -> src\app\root-store\root-store.module.ts
Do I have to manage some high level states directly in root-store ?
Can you show me how you're importing the ItsmStoreActions? Like what does you ts import statement look like?
If you can, post a repo on stackblitz or github recreating the issue. Then we can resolve together. Thanks!!
I have sent a screenshot with organization of files and the code of ItsmActions import.
The import is only in the itsm-store/index.ts ?
you may have to directly import the itsm-store/actions.ts to avoid the duplicate/circular imports. When I get off work I will look into this more.
Thanks for the feedback Daniel! We will get this figured out. And I will add some notes to the article so that others don't stumble on this issue.
I can't publish all the code to a github repo, it's too big. I will build a little appli with the essential of the code.
It's a good idea, so I will test the Store without all the views and the backend.
Great idea. I always try to recreate things in isolated mini repos.
I have forked your project and added a second feature store: hoax ;-)
joke-store/effects can only return action of type koke-actions/actions. So I have imported the main hoax actions and that is running, even if the list of jokes is not proposed.
This is not practical nor clean because I will have about 10-12 main features in the menu after login (AUTH).
With this technique, I need to import all the initial actions of all features into all feature actions. 12 * 12 imports ...
English is not my mother language, I hopeyou understand my explainations.
You can see my changes in github.com/dlucazeau/angular-ngrx-...
I will continue to research this important aspect for our application.
I will go from one menu / item to another directly with the router. And the first step after that will be to activate the feature store. It works well.
As we must be able to install this on-site application with all or only a few features, this architecture will be suitable.
I will study the lazzy loading of the stores.
Your tutorial was a good introduction to solve my problem.
I plan on updating my article soon to accommodate for lazy loading feature stores, I will also address dispatching actions between feature stores
I will monitor and read the news carefully.
Lazy loading is easy, we have just to move the featureModules from AppModule in their corresponding module.
In DevRedux we can see a new line with 'update-reducers'
Agreed.