
Angular 2 Store and NgRx are two powerful tools for managing state in Angular applications. NgRx is a state management library that helps you manage global state by providing a single source of truth.
It's built around the concept of a single store, which is a centralized location for all application state. This store is essentially a database that holds all the data for your application.
By using NgRx, you can easily manage and share data between different parts of your application. This makes it easier to maintain and scale your application as it grows.
In the next section, we'll dive deeper into how NgRx works and how you can use it to manage state in your Angular application.
If this caught your attention, see: Data Lake Store
Getting Started
Angular 2 Store is a library that helps you manage your application's state by providing a simple and efficient way to store and retrieve data. It's built on top of the popular Redux library, which you'll learn more about as you continue reading.
First, you'll need to install the Angular 2 Store library using npm or yarn. This will give you access to the Store class, which is the core of the library. You can install it by running the command npm install @angular-redux/store or yarn add @angular-redux/store.
The Store class is a singleton, meaning there's only one instance of it in your application. This makes it easy to access and manipulate the state from anywhere in your code. You can inject the Store instance into your components using the @Injectable decorator.
To get started with Angular 2 Store, you'll need to create a reducer function that defines the initial state of your application. This reducer function will be responsible for handling actions and updating the state accordingly. You can create a reducer function by using the createReducer function from the @angular-redux/store library.
Once you have your reducer function set up, you can use the Store class to dispatch actions and update the state of your application. You can dispatch actions using the dispatch method, which takes an action object as an argument. The action object should contain a type property that identifies the action being dispatched.
Worth a look: Tiktok Coming Back to App Store
Managing State
State management within Angular started out as a single controller managing all the state for the application, but this approach was limited and led to shared mutable state, which is a recipe for disaster.
To manage complex state, Redux introduced an elegant, yet profoundly simple way to manage application state, and it works really well with Angular. Redux is a library, but more importantly, it's a design pattern that is completely framework agnostic.
State always flows down, meaning that state is passed from parent to child components, and this is a huge shift from how we've approached Angular applications in the past. We no longer need change detection if we're not directly mutating data within our component.
To listen for changes in the store, you can use the watch method, which returns an RXJS Observable, allowing you to use the power of the RXJS library. You can also watch keys before you create them and then when you create them, the subscribers will be notified.
The reducer is the crux of state management for Redux-ish patterns, and it's the thing that catches and handles the actions that are dispatched from your smart components, and it's also the thing that actually resets the state to a new, modified state.
To hook up your reducer in your NgModule block, you need to call StoreModule.provideStore and pass in the names of your reducer(s). This sets up the store for your application, allowing you to manage state in a predictable and maintainable way.
Using functional programming techniques, you can write functions in which you can predict the outcome just by looking at the function inputs and the body of the function. This is the exact opposite of the object-oriented approach, in which data and methods are coupled in your code.
Reducers take one state object and an action to perform, and they return a new state object based on the action. In the case of the items reducer, it performs actions on a list of items, and in the case of the selectedItem reducer, it handles the currently selected item.
To manage our application state, we need to create our items and selectedItem reducers, and these reducers will handle specific actions and return new state objects based on those actions.
Async and Events
In the world of Angular 2, we have a companion module to ngrx/store called ngrx/effects that helps us get async data into our state object in the store.
This module is a game-changer when it comes to managing our state with async operations, but it deserves its own blog post to do it justice. Stay tuned for part two of this project when we'll dive deeper into ngrx/effects.
Intriguing read: When Storing Products It Is Important to
Hungry for Async?
As you start working with ngrx/store, you'll eventually wonder how to get async data into your state object. This is where ngrx/effects comes in, a companion module that helps you intertwine your state with async operations.
You can create a service to pull data from the store, like the ItemsService in Example 2, which exposes the items collection by pulling it from the store. This service is essential when introducing asynchronous operations.
To make HTTP calls, you'll need to import Http and Headers from angular2/http, as shown in Example 3. This will allow you to define a BASE_URL constant and create a HEADER constant to communicate with your server.
Readers also liked: Cloud Data Store
When making HTTP calls, you'll often need to pipe results through additional operators, like map, to parse and transform your data. This is demonstrated in the loadItems method in Example 3, where the results are parsed and transformed before being dispatched to the reducer.
The key is to subscribe to the observable sequence and then hand off control to your reducer by dispatching the transformed results. This is a crucial step in handling async data in ngrx.
Events Flow Up
In Redux, user events are captured and emitted up to a reducer for processing. This is a key difference from Angular 1.x, where it was common to see bloated controllers with large chunks of logic dedicated to managing local state.
Events flow up, meaning that they are emitted from child components to their parent components and then onto the reducer. This is a fundamental concept in Angular 2, where dumb controllers are used to capture events and emit them via output to their parent controller.
All roads lead to the reducer, which is the central hub for processing events. In Example 1, we can see two event flows: one where an event is emitted from a child component to its parent component and then onto the reducer, and another where an event is emitted to a service to perform an asynchronous operation and then the result is emitted into the reducer.
In Angular 2, the burden placed upon components becomes negligible by moving logic that can directly manipulate state to reducers. This is a significant improvement over the bloated controllers of Angular 1.x. By moving logic to reducers, components can focus on what they do best: capturing events and emitting them to their parent components.
Additional reading: 3 1 2 Minutes
NgRx Fundamentals
NgRx is a powerful library that combines the power of Redux with the power of observables, making state management in Angular 2 exponentially easier.
The icing on the cake is that state moving through an Angular 2 application is exponentially easier with the introduction of observables and the async pipe, thanks to the introduction of @ngrx/store.
DELETE_ITEM returns a new array by filtering out the item that we want to delete, making it a great example of how NgRx simplifies state management.
NgRx uses a Redux-like pattern to manage state, but with the added power of observables, making it a very, very powerful stack.
The reducer is the crux of state management for all of these Redux-ish patterns, and it is the thing that catches and handles the actions that are dispatched from your smart components.
The reducer is a function that accepts the state and an Action, and returns a new state defined by your State interface.
NgRedux is a library that helps you get Angular 2 aware of Redux, and it's available on npm via npm install ng2-redux.
To register NgRedux as a provider with Angular 2, you need to import provider from ng2-redux, and tell Angular to use this during the bootstrap phase of your application.
State management within Angular started out as a single celled organism, but with the introduction of NgRx, we can now manage complex state within our applications in a much more elegant and simple way.
State and Complexity
Reducing complexity is key to writing efficient code, and functional programming techniques can help achieve this by making it possible to predict the outcome just by looking at the function inputs and body.
The object-oriented approach, on the other hand, couples data and methods in code, making it harder to understand and debug. By using functional programming for data that represent the state and object-oriented approach for data that are not part of the state, you can reap the benefits of both approaches.
Immutable data is another benefit of functional programming, allowing you to track changes by creating a new version from the last value, making it easier to investigate unexpected behavior.
Closing the Loop
The Redux Loop is a game-changer for managing complex state in applications. It's a one-way data flow that eliminates the need for change detection.
State always flows down, starting from the top-level component and trickling down to child components. This is a huge shift from the traditional approach of manipulating data directly in components.

We can see this in action in the App component, where the items and selectedItem properties are set once and never changed again. This is a key aspect of the Redux Loop.
The full Redux Loop is implemented using ngrx, which provides a robust and scalable solution for managing state. This loop is not just a library, but a design pattern that works well with Angular.
By closing the loop, we can eliminate shared mutable state and its associated problems. This is a major win for developers, who can now focus on building robust and maintainable applications.
Reducing Complexity Functionally
Functional programming techniques allow you to write functions that can predict their outcome just by looking at the function inputs and body. This is the opposite of the object-oriented approach, where data and methods are coupled in your code.
Immutable data is another benefit of functional programming, where changes create a new version of the last value. This makes it easier to investigate unexpected behavior by looking at the current state and tracing back to the point when things started to go wrong.
Module hot reloading is a feature that allows you to fix your code and replace parts of your app without refreshing the browser. This is made possible because your state is stored separately from your components.
With functional programming, you can decouple your data and methods, reaping the benefits of both object-oriented and functional approaches. This is especially useful when dealing with complex state management in applications.
Testing and Setup
Testing and setup are crucial parts of building an Angular 2 store. The surface area that contains testable logic has been vastly reduced because Redux reducers are pure functions with a clear contract.
In fact, testing reducers is very easy, and the initial state plays a significant role in it. To test a reducer, you need to know exactly what you should get back when you send an action to it, which is straightforward with Redux.
The tests were really easy to write because we start with an initial state and when we send an action to our reducer, we know exactly what we should get back. We can easily articulate the expected result for the remaining two reducer's methods and then write assertions for them.
Setting Up
When you start writing tests for your Angular 2 application, you'll need to set up a testing harness. This involves importing the necessary items and methods from Angular2/testing.
Angular 2 now uses Jasmine by default, so you'll be working with Jasmine methods. For reference, the skeleton of your test spec should look like this: describe('Items', () => { ... }).
Your test spec will likely have multiple describe blocks, each with its own set of it blocks. Each it block should have a clear description of what you're testing. The initial state of your application is crucial in writing tests, as it will be used as the starting point for each test.
In your test spec, you'll import items and selectedItems, as well as the describe and expect methods from Angular2/testing. This is where the testing magic happens. By importing these methods, you'll be able to write assertions for your tests.
Check this out: How Do You Set up an Ebay Shop
Bonus: Testing

Testing is a crucial part of any application, and Redux makes it surprisingly easy.
One of the most important aspects of Redux is that it is very easy to test reducers because they are pure functions with a clear contract. This means that reducers are predictable and consistent, making them a joy to test.
Reducers are really easy to test because the methods are pure and the contract is crystal clear. This is a major advantage over other state management systems.
Let's take a look at an example of how to write a test for a reducer. We want to test the items reducer with an action type of CREATE_ITEM, and we would expect that the result would be the initial array plus the new item.
Here's an example of how to write the test:
```
expect(stateItems).toEqual(payload);
```
We can also test the DELETE_ITEM action, and we would expect that the result would be the initial array minus the item with the specified id.
Discover more: Pure Cloud Block Store

Here's an example of how to write the test:
```
it('DELETE_ITEM', () => {
let payload = { id: 0 },
result = [ initialState[1] ],
stateItems = items(initialState, {type: 'DELETE_ITEM', payload: payload});
```
It's worth noting that the surface area that contains testable logic has been vastly reduced, making it easier to write and maintain tests.
Evolution and Architecture
Angular's evolution in state management has been a journey. We started with a single controller managing all the state for the application, which was a simple approach but not scalable.
As our applications grew, we began to group our views and controllers into smaller, self-contained units, either within a directive or a route. This was a vast improvement, but we still struggled with managing complex state.
The introduction of Redux fundamentally changed the way we approach state-management, and it's now a widely adopted design pattern that works well with Angular. Redux is a library, but more importantly, it's a design pattern that's completely framework agnostic.
Modern web apps often include complex relationships between various parts, making it difficult to manage state. One approach to dealing with this complexity is to store all of the app state in a single object, separately from the components.
Frequently Asked Questions
Which is better NgRx store or signal store?
Choose NgRx Store for complex applications with shared state and strong debugging needs, or Signals for simple, localized scenarios with faster setup. The right choice depends on your project's specific requirements and complexity.
Featured Images: pexels.com


