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:

import { Component, OnInit } from '@angular/core';
import { CompanyService } from '../company.service';
import { Observable } from 'rxjs/Observable';
import { Store } from '@ngrx/store';
import { Company } from '../../models';
import { AppState } from 'app/models/appState';
import * as companyAcitons from './../../actions/company.actions';
 
@Component({
  selector: 'app-company-list',
  templateUrl: './company-list.component.html',
  styleUrls: ['./company-list.component.scss'],
})
export class CompanyListComponent implements OnInit {
 
  companies$: Observable<Company[]>;
 
  constructor(private store: Store<AppState>) { }
 
  ngOnInit() {
    this.loadCompanies();
    this.companies$ = this.store.select(state => state.companies.companies);
  }
 
  loadCompanies() {
    this.store.dispatch(new companyAcitons.LoadCompaniesAction());
  }
 
  deleteCompany(companyId: number) {
    this.store.dispatch(new companyAcitons.DeleteCompanyAction(companyId));
  }
}

Effects

Sources

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