Outils pour utilisateurs

Outils du site


web:javascript:angular:ngrx

Ceci est une ancienne révision du document !


ngrx

ngrx est une librairie qui permet de gérer l'état de l'application. C'est l'implémentation du pattern redux.

Installation

$ npm install @ngrx/core @ngrx/effects @ngrx/store @ngrx/store-devtools --save

Actions

Fichier nommé avec suffixe .actions.ts, par exemple company.actions.ts.

import { Company } from '../models/company';
 
export const LOAD_COMPANIES = 'LOAD_COMPANIES';
export const LOAD_COMPANIES_SUCCESS = 'LOAD_COMPANIES_SUCCESS';
 
export class LoadCompaniesAction {
  readonly type = LOAD_COMPANIES;
  constructor() {}
}
 
export class LoadCompaniesSuccessAction {
  readonly type = LOAD_COMPANIES_SUCCESS;
  constructor(public payload Company[]) {}
}
 
export type Action
  = LoadCompaniesAction
  | LoadCompaniesSuccessAction;

Reducer

Fichier avec le suffixe .reducer.ts, par exemple company.reducer.ts.

import * as companyActions from '../actions/company.actions';
 
export function companyReducer(state = [], action: companyActions.Action) {
  switch (action.type) {
    case companyActions.LOAD_COMPANIES_SUCCESS: {
      return action.payload;
    }
    default: {
      return state;
    }
  }
}

The Store

Dans app.module.ts:

import { StoreModule } from '@ngrx/store';
import { companyReducer } from './reducers/company.reducer';
 
 
// ...
 
  imports: [
    // ...
    StoreModule.forRoot({ companies: companyReducer });
 
  ]

Dans le component:

 

Effects

Sources

web/javascript/angular/ngrx.1524357016.txt.gz · Dernière modification : 2022/02/02 00:43 (modification externe)