Angular ngrx
Introduction
ngRx is a version of redux built for Angular. It provides,
- Centralize immutable state
- Performance
- Testability due to use of pure functions
- Tooling, advance logging, visualize state tree
Redux Pattern
It provides a “unidirectional data flow” that helps to manage and organise data better and makes debugging a lot easier.
- the UI dispatches an action to the reducer
- the reducer sends the new state to the store
- the store, sets the state in the reducer, and notifies the selector
- the selector sends out new state event to all subscribed observers
- Store, single source truth for state,
- Don not sotr unshared status, angular state
- Non serailizable state
- Actions, Dispatch action to change state
- Reducers, used to change state state, examples
- set user details property on login,
- toggle table a side menu visible
- set global spinner visible property
When to Use ngRx
- provides a place for UI state to retain ti between router views
- provides client-side cache to use as needed
- reducer updates the store and the store notifies all subscribers
- it has great tooling
Sample Application Architecture
Captured this be is kinda gives an approach for small apps and where to start. Somethings it is the size of the task which can distract people from starting it.
Walkthrough a Change
Introduction
Redux follows a pattern regardless of the problem you are trying to solve. This may look like the React Redux Page after I have finished.
Process
We are going to update the display product code state.
- User issues a click
- The component dispatches an action to the reducer
- The reducer uses the action as input and the current state from the store to create new state
- The reducer sends the state to the store
- The store broadcasts the state to all subscribers, in this case the component
- Component updates it's bound property
Installing Packages
Initializing the Store
Installing
Using the angular cli app.modules.ts is updated along with packages.json
ng add @ngrx/store
This makes the following changes
import { StoreModule } from '@ngrx/store';
...
@NgModule({
imports: [
BrowserModule,
...
StoreModule.forRoot({}, {})
],
Module Considerations
For modules, like the router module, there is a forFeature equivalent of the StoreModule. We can, just like react have multiple reducers for a feature too. Each reducer is stored using tag/value.
StoreModule.forFeature('products', {
'productList': listReducer,
'productData': dataReducer
})
Installing DevTools
First install the tools
ng add @ngrx/store-devtools
Initialize in the app module with
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
...
@NgModule({
imports: [
BrowserModule,
...
StoreDevtoolsModule.instrument({
name: 'Application Name to Recognise'
maxAge: 25,
logOnly: environment.production
})
],
Defining State and Actions
This code defines an action on the fly.
Building a Reducer
The function return a copy of the state not a modified state by ... (spreading) the original state and adding or replacing the new state.
import { createReducer, on, createAction } from '@ngrx/store';
export const productReducer = createReducer(
{showProductCode: false},
on(createAction('TEST'), state => {
console.log('Old state is:' + JSON.stringify(state))
return {
...state,
showProductCode: !state.showProductCode
}
})
)
Do not forget to update the module to have the reducer assigned.
...
StoreModule.forFeature('products', productReducer)
...
Dispatching an Action
We need to inject the store into the component and dispatch the action. We do this using dependency injection and for the store and the Angular checkChanged to to initiate the dispatch.
...
constructor(
private productService: ProductService,
private store: Store<any>) { }
..
checkChanged(): void {
this.store.dispatch({
type:
'[Product] toggle product code'})
}
Subscribing to the Store
We subscribe to the store using the name we used in the module. This can be done in the ngOnInit function for Angular. The products is the name we used when initializing the store the module code.
this.store.select('products').subscribe(
products => {
if(products) {
this.displayCode = products.showProductCode
}
}
)