Upgrade to Pro — share decks privately, control downloads, hide ads and more …

NgRx v6 - Angularでの状態管理 -

puku0x
September 27, 2018

NgRx v6 - Angularでの状態管理 -

Angular触ろうの会 in Fukuoka #6

puku0x

September 27, 2018
Tweet

More Decks by puku0x

Other Decks in Technology

Transcript

  1. @puku0x NgRx RxJSベースのRedux • Store • Action • Reducer •

    Effects $ ng new my-app $ cd my-app $ npm install @ngrx/store $ npm install @ngrx/effects
  2. Store 状態・データの置き場 export interface State { todos: Todo[]; loading: boolean;

    } export const initialState: State { todos: [], loading: false, });
  3. Action イベント export enum TodoActionTypes { CreateTodo = '[Todo] Create',

    CreateTodoSuccess = '[Todo] Create Success', } export class CreateTodo implements Action { readonly type = TodoActionTypes.CreateTodo; constructor(public payload: { todo: Todo } ) {} }
  4. export function reducer(state = initialState, action: TodoAction): State { switch

    (action.type) { case TodoActionTypes.CreateTodo: { return { ...state, loading: true }; } default: { return state; } } } Reducer
  5. @Effect() createTodo$: Observable<Action> = this.actions$.pipe( ofType<CreateTodo>(TodoActionTypes.CreateTodo), concatMap(action => { const

    { todo } = action.payload; return this.todoService.create(todo).pipe( map(result => new CreateTodoSuccess({ todo: result })), catchError(error => of(new CreateTodoFail({ error }))) ); }) ); Effects
  6. export class TodoFacade { loading$ = this.store.pipe(select(todoQuery.getLoading)); todos$ = this.store.pipe(select(todoQuery.getTodos));

    createSuccess$ = this.actions$.pipe(ofType<CreateTodoSuccess>(...)); create(todo: Todo) { this.store.dispatch(new CreateTodo({ todo })); } } Facade
  7. import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity'; export interface

    State extends EntityState<Todo> { } export const adapter: EntityAdapter<Todo> = createEntityAdapter<Todo>(); export const initialState: State = adapter.getInitialState({ }); export function reducer(state = initialState, action: TodoActions): State { switch (action.type) { case TodoActionTypes.CreateTodoSuccess: { return adapter.addOne(action.payload.todo, { ...state, loading: false }); } } @ngrx/entity
  8. export const entityMetadata: EntityMetadataMap = { Todo: {}, }; @NgModule({

    imports: [ NgrxDataModule.forRoot({ entityMetadata }) ], }) export class AppStoreModule { } ngrx-data