This post is meant to explain some of the magic behind the line of initialization code for Ngrx/Store that you put in the imports block of the NgModule. Working with provideStore is key to understanding how to setup your project wiht Ngrx, so let's get into it!
In the app.module file of your application you should have something like this:
Now, in order to let our application know that we want to use Ngrx we just need to add one line to our imports array (not including the import statement at the top of the file bringing in StoreModule from "@ngrx/store"). The line we'll add looks something like this:
The providerStore function takes an object of one or more reducers (functions of type ActionReducer). ProvideStore also takes an additional optional argument which is an initial state to use. I tend to leave this argument off and just provide an initial state to each reducer. Remember, our reducer function looks something like this:
In the code above we're exporting a constant myReducer, which is of type ActionReducer, and I'm telling it that this ActionReducer takes a State defined by my interface AppState which looks like this:
Notice that this AppState interface is built from two other custom types: User and Bullet. I've also defined interfaces for them, and they look like this:
And I'm also defining an initial state which looks like this:
Well, that's all there really is to setting up Ngrx and using provideStore. Now in your smart component or service you can inject store, dispatch events to your reducers, and subscribe to slices of the state like this:
And remember, the global state is created from the state of each of our reducers that we pass into provideStore. Since we're only providing one reducer in this case our GlobalState would look like this:
The posts on this site are written and maintained by Jim Lynch. About Jim...