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

Introduction

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));
  }
}

AppStateest une interface:

import { Company } from './company';
 
export interface AppState {
    companies: { companies: Company[] }
}

on peut créer une interface avec ng g interface models/appState.

Effects

Fichier company.effects.ts:

import { Injectable } from '@angular/core';
import { Actions, Effect, toPayload } from '@ngrx/effects';
import 'rxjs/add/operator/switchMap';
 
import { CompanyService } from '../company/company.service';
import * as companyActions from './../actions/company.actions';
import { DeleteCompanySuccessAction } from '../actions/company.actions';
 
@Injectable()
export class CompanyEffects {
    constructor(
        private actions$: Actions,
        private companyService: CompanyService
    ) { }
 
    // tslint:disable-next-line:member-ordering
    @Effect() loadCompanies$ = this.actions$
        .ofType(companyActions.LOAD_COMPANIES)
        .switchMap(() => {
            return this.companyService.loadCompanies()
                .map(companies => new companyActions.LoadCompaniesSuccessAction(companies));
        });
 
    // tslint:disable-next-line:member-ordering
    @Effect() deleteCompany$ = this.actions$
        .ofType(companyActions.DELETE_COMPANY)
        .switchMap((action: companyActions.DeleteCompanyAction) => {
            return this.companyService.deleteCompany(action.payload)
                .map(company => new companyActions.DeleteCompanySuccessAction(company.id));
        });
};

Sources

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