|
| 1 | +import { Injectable } from '@angular/core'; |
| 2 | +import { Actions, Effect } from '@ngrx/effects'; |
| 3 | +import { |
| 4 | + ItemsActions, |
| 5 | + ItemsActionTypes, |
| 6 | + LoadItems, |
| 7 | + ItemsLoaded, ItemUpdated, ItemDeleted, AddItem, UpdateItem, DeleteItem, ItemAdded |
| 8 | +} from './items.actions'; |
| 9 | +import { ItemsState } from './items.reducer'; |
| 10 | +import { DataPersistence } from '@nrwl/nx'; |
| 11 | +import { ItemsService } from '../items/items.service'; |
| 12 | +import { map } from 'rxjs/operators'; |
| 13 | +import { Item } from '../items/item.model'; |
| 14 | + |
| 15 | +@Injectable() |
| 16 | +export class ItemsEffects { |
| 17 | + @Effect() effect$ = this.actions$.ofType(ItemsActionTypes.ItemsAction); |
| 18 | + |
| 19 | + @Effect() |
| 20 | + loadItems$ = this.dataPersistence.fetch(ItemsActionTypes.LoadItems, { |
| 21 | + run: (action: LoadItems, state: ItemsState) => { |
| 22 | + return this.itemsService.all().pipe(map((res: Item[]) => new ItemsLoaded(res))) |
| 23 | + }, |
| 24 | + |
| 25 | + onError: (action: LoadItems, error) => { |
| 26 | + console.error('Error', error); |
| 27 | + } |
| 28 | + }); |
| 29 | + |
| 30 | + @Effect() |
| 31 | + addItem$ = this.dataPersistence.pessimisticUpdate(ItemsActionTypes.AddItem, { |
| 32 | + run: (action: AddItem, state: ItemsState) => { |
| 33 | + return this.itemsService.create(action.payload).pipe(map((res: Item) => new ItemAdded(res))) |
| 34 | + }, |
| 35 | + |
| 36 | + onError: (action: AddItem, error) => { |
| 37 | + console.error('Error', error); |
| 38 | + } |
| 39 | + }); |
| 40 | + |
| 41 | + @Effect() |
| 42 | + updateItem$ = this.dataPersistence.pessimisticUpdate(ItemsActionTypes.UpdateItem, { |
| 43 | + run: (action: UpdateItem, state: ItemsState) => { |
| 44 | + return this.itemsService.update(action.payload).pipe(map((res: Item) => new ItemUpdated(res))) |
| 45 | + }, |
| 46 | + |
| 47 | + onError: (action: UpdateItem, error) => { |
| 48 | + console.error('Error', error); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + @Effect() |
| 53 | + deleteItem$ = this.dataPersistence.pessimisticUpdate(ItemsActionTypes.DeleteItem, { |
| 54 | + run: (action: DeleteItem, state: ItemsState) => { |
| 55 | + return this.itemsService.delete(action.payload).pipe(map(_ => new ItemDeleted(action.payload))) |
| 56 | + }, |
| 57 | + |
| 58 | + onError: (action: DeleteItem, error) => { |
| 59 | + console.error('Error', error); |
| 60 | + } |
| 61 | + }); |
| 62 | + |
| 63 | + constructor( |
| 64 | + private actions$: Actions, |
| 65 | + private dataPersistence: DataPersistence<ItemsState>, |
| 66 | + private itemsService: ItemsService |
| 67 | + ) {} |
| 68 | +} |
0 commit comments