@ngrx store normalized State Shape - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki

Normalized state shape sample

{
  ui: {
    loading: false,
    error: ''
  },
  entities: {
    users: {
      'admin': {
        id: 'admin',
        password: '123456'
      }
    },
    dashboards:{
      1: {
        id: 1,
        user: 'admin',
        name: '',
        tabIds: [1, 2, 3]
      },
      2: {
        id: 2,
        user: 'admin',
        name: '',
        tabIds: [4, 5]
      }
    },
    tabs: {
      1: {
        id: 1,
        name: '',
        rows: 12,
        columns: 12,
        widgetIds: {
          1: {
            id: 1,
            x: 0,
            y: 0,
            w: 2,
            h: 3
          },
          2: {
            id: 2,
            x: 0,
            y: 0,
            w: 2,
            h: 3
          }
        }
      }
    },
    widgets: {
      1: {
        id: 1,
        user: 'admin',
        name: 'Widget 1',
        dataStream: ''
      },
      2: {
        id: 2,
        user: 'admin',
        name: 'Widget 2',
        dataStream: ''
      }
    }
  }
}

ngrx-normalizr

Schema

  • Define relations of data
import { schema } from 'normalizr';

export class User {
    id: string;
    displayname: string;
    password: string;
}

export class Widget {
  id?: number;
  user: User;
  name: string;
  type: string;
  dataStream: string;
  defaultSize: WidgetSize;
}

export const userSchema = new schema.Entity('users');
export const widgetSchema = new schema.Entity('widgets', {user: userSchema});

Action Creators

  • setData - (data: T[]) => SetData<T>: used for resetting entity state data
  • addData - (data: T[]) => AddData<T>: existing entities will be overwritten by updated data or new data
  • removeData - (id: string, removeChildren?: SchemaMap) => RemoveData: remove the entity including its children or not (cascade)
const creators = actionCreators<Widget>(widgetSchema);
export const setWidgetData = creators.setData;
export const addWidgetData = creators.addData;
export const removeWidgetData = creators.removeData;

Used in Effect

     this.loadAll$ = this._actions$
      .ofType(widgetList.LOAD)
      .switchMap(() =>
        this._widgetService.getAll()
          .mergeMap((widgets: Widget[]) => {
            return [widgetList.addWidgetData(widgets), new widgetList.LoadSuccess(widgets)];
          })
          .catch(error => Observable.of(new widgetList.LoadFail(error.toString())))
      );

Query State data

Create Schema selectors

const schemaSelectors = createSchemaSelectors<Widget>(widgetSchema);

Selectors

  • getEntities -> MemoizedSelector<{}, T[]>: returns all denormalized entities
  • getNormalizedEntities -> MemoizedSelector<any, EntityMap>: returns all normalized (raw state) entities

Read more: https://michaelkrone.github.io/ngrx-normalizr/

⚠️ **GitHub.com Fallback** ⚠️