Angular ngrx

From bibbleWiki
Revision as of 05:45, 5 September 2020 by Iwiseman (talk | contribs) (Combining)
Jump to navigation Jump to search

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

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<ProductState>(
    initialState,
    on(createAction('TEST'), (state) : ProductState => {
        return {
            ...state,
            showProductCode: !state.showProductCode
        }
    })
)

Do not forget to update the module to have the reducer assigned.

...
    StoreModule.forFeature('products', productReducer)
...

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';

...
  constructor(
    private productService: ProductService,
    private store: Store<State>) { }
..
  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. (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
    )