As you may have guessed from the title, this post is all about understanding what selectors are in an Ngrx Angular 2 application and why one should want to use them. I'll admit it; for a while I didn't use selectors at all. The truth is that you don't *need* them to get a basic project up and running with Ngrx (and that's why I don't talk about them in my Getting Set Up With With Ngrx blog post), but as your application grows along with your understanding of Ngrx you may eventually want to refactor your code and the way you select data from the state to improve your project's consistency and prevent unnecessary duplication. So without further ado, let's talk about selectors!
Let's suppose that we are in a "smart" component, and we want to read some property off of our state so that it can be passed along to the dumb component and displayed on the screen. How would we do that? This is the Angular world, and one thing that's been a consistent value from AngularJS 1.1 all the way up to Angular 2 (and probably far on into the future of Angular) is the use of dependency injection. We inject the Store into our component via the constructor:
Because ngrx is based on observables and reactive programming, we can use this store object to basically "hook up" a variable in our component to the data in our store, and whenever the store's state changes the component is aware of this change and can update its own property or properties. Also notice that the store object is typed to a Store type (from the Ngrx library), and thid takes a GlobalState type (which I'll talk about in a bit). In order to do this "hooking up" functionality we use the select method from the Ngrx library:
It would be nice to have some context as to what we are actually selecting so I've contrived a simple example to illustrate how all the redux pieces come together when we select data from the store. First, let's define the state we will use. TypeScript is nice because it supports the concept of an interface, and here I've created an interface called MyState for a simple state object with two properties: userData, an object and contains a single number property named totalScore, and currentVideos, which is an array of objects of some undeclared data type.
I've also created a constant called initialState which conforms to the state interface and declares initial values for the various properties of the state object.
We'll then create a reducer to handle any Ngrx actions that are dispatched. Notice our ActionReducer uses the generics feature of TypeScript and takes another type; the type defined by our state interface.
We then add this line to our NgModule to let the core Ngrx library know that we would like to use this reducer.
When we use multiple reducers and stores Ngrx will behind the scenes combine them into one global state. We'll need this global state later when we are injecting our store object, but for now just know that the global stat interface is basically an object whose properties' types are the interfaces for the various state interfaces we are using in our app.
Ok! Now we've got all the plumbing in place for using Ngrx, and we're ready to select some data from our store. We'll first need to grab a reference to the Ngrx State service through dependency injection:
Then we'll normally set up our selector either in our constructor in some lifecycle hook like ngOnInit. You could also execute your select statement later, but since the select method just hooks up your data to the store and from then on watches for updates, it almost always makes sense to start selecting from the store when the component starts up.
)Here's an example of what I call the "pure string selector". Notice that we are calling the select method on our store object, and as an argument into it we are passing a string that is the name of our reducer (or whatever top-level name we gave our store in the NgModule provideStore() method):
While this works, we don't get any help from our IDE to tell us that we are indeed trying to access properties that actually exist. In addition, I then need to "unpack" the data object inside of the subscribe method.
Any experienced programmer will probably be aware that hardcoding strings can bring big-time problems from careless mistakes. With this method that I call "interface hardcoding" we can get rid of the hardcoded string by replacing it with an arrow function that "drills down" into our state to return the slice we desire.
This is a little better that using pure strings because the IDE will immediately tell us if we spell something wrong or are trying to access a property that does not exist for that state's interface. The only downside to this is that if we want to select this data in multiple places (such as multiple components) then I am hardcoding this arrow function and and duplicating this drilling logic. If we decide later that we want to change our state object interface then we need to manually go into every file that is hardcoded for the old interface and update them. Ain't nobody got time for that!
The encapsulated selector gives us the benefits of IDE type support like the interface hardcoding, but here we do an extra step where we extract the hardcoded piece out. For example, here's an encapsulated constant called getCurrentVideosArray that contains the logic for pulling the videos out of our store:
I can then simply use this constant inside of my select method like so:
Now if you ever need to change your underlying interface you can just change it in one place- the getCurrentVideosArray const.
That's all for this post! So, what do you think? Have I convinced you of the power and beauty of encapsulated selectors? Let me know in the comments below! ;)
The posts on this site are written and maintained by Jim Lynch. About Jim...
Want FREE access to
my daily stock tips
Sign up here:
- Triple Gainers
- Rippers N' Dippers
- Growingest Growers