import { Injectable } from '@angular/core'; import { Actions, Effect, ofType } from '@ngrx/effects'; import { Observable, of } from 'rxjs'; import { map, switchMap, catchError } from 'rxjs/operators'; import { Action } from '@ngrx/store'; import * as customerActions from '../actions/customer.actions'; import { CustomerService } from '@app/domain/services/customer.service'; import { AppMessageService } from '@app/shared/app-message.service'; import { globals } from '@app/shared/global'; @Injectable() export class CustomerEffects { constructor( private readonly actions$: Actions, private readonly customerSvc: CustomerService, private readonly msgSvc: AppMessageService ) { } @Effect() loadCustomers$: Observable = this.actions$.pipe( ofType(customerActions.FETCH), switchMap(() => this.customerSvc.loadCustomers().pipe( map(customers => new customerActions.FetchSuccess(customers)), catchError(err => { this.msgSvc.addFailedMsg(globals.doThingsFailed.replace('#do#', globals.load).replace('#thing#', globals.customers)); return of(new customerActions.FetchError()); }) ) ) ); @Effect() createCustomer$: Observable = this.actions$.pipe( ofType(customerActions.CREATE), switchMap(({ payload }) => this.customerSvc.saveCustomer(payload).pipe( map((customer) => new customerActions.CreateSuccess(customer)), catchError(err => { this.msgSvc.addFailedMsg(globals.doThingsFailed.replace('#do#', globals.create).replace('#thing#', globals.customer)); return of(new customerActions.CreateFailed()) }) ) ) ); @Effect() updateCustomer$: Observable = this.actions$.pipe( ofType(customerActions.UPDATE), switchMap(({ payload }) => this.customerSvc.saveCustomer(payload).pipe( map(() => new customerActions.UpdateSuccess(payload)), catchError(err => { this.msgSvc.addFailedMsg(globals.doThingsFailed.replace('#do#', globals.save).replace('#thing#', globals.customer)); return of(new customerActions.UpdateFailed()); }) ) ) ); @Effect() deleteCustomer$: Observable = this.actions$.pipe( ofType(customerActions.DELETE), switchMap(({ payload }) => this.customerSvc.deleteCustomer(payload).pipe( map(() => new customerActions.DeleteSuccess(payload)), catchError(err => { this.msgSvc.addFailedMsg(globals.doThingsFailed.replace('#do#', globals.delete).replace('#thing#', globals.customer)); return of(new customerActions.UpdateFailed()) }) ) ) ); }