Angular ngrx: Difference between revisions
Line 237: | Line 237: | ||
... | ... | ||
import { State } from '../state/product.reducer'; | import { State } from '../state/product.reducer'; | ||
import * as ProductActions from './../state/product.actions' | |||
... | ... | ||
constructor( | constructor( | ||
Line 244: | Line 244: | ||
.. | .. | ||
checkChanged(): void { | checkChanged(): void { | ||
this.store.dispatch( | this.store.dispatch(ProductActions.toggleProductCode()) | ||
} | } | ||
Revision as of 06:16, 5 September 2020
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
Selector
In the example a new item for Redux was created compared to the React version. This was a selector. I guess it is a product differentiater. The benefits were
- Provide a strongly type API
- Decouple the store from the components
- Encapsulate complex data transformations
- Reusable
- Memoized (cache)
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
Module State
To define state, we have typescript so we can be a bit better by using the interfaces not available in JS at the time In the module specific state we have
export interface ProductState {
showProductCode: boolean;
currentProduct: Product;
products: Product[]
}
App State
For the app we might have wanted to do the following
export interface State {
products: ProductState;
user: any
...
}
But this breaks the Lazy Loading as the module code is lazy loaded. And omitting the products from the App State but leaving the users as this is not lazy loaded so it is recommended we omit the states in the app state and extend the module state to include the app state.
export interface State {
user: any
}
Extending the Module State
Because of Lazy Loading we cannot specify all of the state for the app in the App state. In the module we may need the state of other components so to work around this we extend the state in the module to include the app state.
import * as AppState from '../../state/app.state';
export interface State extends AppState.State {
products: ProductState
}
Initializing the Module State
It is good practice and deterministic to initialise the state. We can do this be defining a const for use with the reducer creation
const initialState: ProductState = {
showProductCode: true,
currentProduct: null,
products: []
}
Defining Actions
Basic
Just make a const to represent the action.
import { createAction } from '@ngrx/store'
export const toggleProductCode = createAction('[Product] Toggle product code')
export const setCurrentProduct = createAction('[Product] Set current product')
export const clearCurrentProduct = createAction('[Product] Clear current product')
export const initCurrentProduct = createAction('[Product] Init current product')
Properties=
Some actions will need properties to work. In the above example this would be setCurrentProduct so we need to add it as a props to pass. In Angular we do this.
import { createAction, props } from '@ngrx/store'
import { Product } from '../product'
...
export const setCurrentProduct = createAction(
'[Product] Set current product',
props<{product: Product}>()
)
Building a Reducer
Reducer with no Parameters
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';
import * as ProductActions from './product.actions'
export const productReducer = createReducer<ProductState>(
initialState,
on(ProductActions.toggleProductCode, (state) : ProductState => {
return {
...state,
showProductCode: !state.showProductCode
}
})
)
Do not forget to update the module to have the reducer assigned.
...
StoreModule.forFeature('products', productReducer)
...
Reducer with Parameters
To use a reducer which has parameters we simply deconstruct the second parameter on the on parameter.
on(ProductActions.setCurrentProduct, (state, params) : ProductState => {
return {
...state,
currentProduct: params.product
}
})
Creating A Selector
Basic
The selector is way to product an enum to get a specific piece of data from the State. Each state section you want you define a selector and and accessor.
const getProductFeatureState = createFeatureSelector<ProductState>('products')
export const getShowProductCode = createSelector(
getProductFeatureState,
state => state.showProductCode
);
Transformation In Selector
So to get the current product we need to get the id and then the relevant product. This was achieved with the following code.
export const getCurrentProductId = createSelector(
getProductFeatureState,
state => state.currentProductId
);
export const getCurrentProduct = createSelector(
getProductFeatureState,
getCurrentProductId,
(state, currentProductId) =>
state.products.find(p => p.id === currentProductId)
);
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. Note We are using the product definition of State and not the App definition as it will lack the product reducer definition.
...
import { State } from '../state/product.reducer';
import * as ProductActions from './../state/product.actions'
...
constructor(
private productService: ProductService,
private store: Store<State>) { }
..
checkChanged(): void {
this.store.dispatch(ProductActions.toggleProductCode())
}
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. (This is an example of what using a selector it is trying to solve)
Without selectors we would have
this.store.select('products').subscribe(
products = this.displayCode = products.showProductCode
)
With Selectors we have
import {State, getShowProductCode } from '../state/product.reducer'
...
this.store.select(getShowProductCode).subscribe(
showProductCode => this.displayCode = showProductCode
)