import { catchError, map, switchMap } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { Actions, Effect, ofType } from '@ngrx/effects'; import { Action, Store } from '@ngrx/store'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import * as errorActions from '../../../actions/errors'; import { DataFetcher } from '../../../services/data-fetcher/data-fetcher.service'; import * as petaDestinationsActions from '../actions/peta-destinations.actions'; import { apiUrls } from '../constants/api.constants'; import { PETADestinationsInterface } from '../models/peta-destinations.interface'; import * as petaReducer from '../reducers'; import { LoadPETAError, LoadPETALoading } from '../actions/peta.actions'; const errorUrl: string = null; @Injectable() export class PETADestinationsRequestEffect { @Effect() getPETADestinationsRequest$: Observable = this.actions$ .pipe( ofType(petaDestinationsActions.LOAD_PETA_DESTINATIONS_ACTION), switchMap((action) => { this.petaStore.dispatch(new LoadPETALoading(true)); const url = apiUrls.BASE_URL + apiUrls.GET_PETA_DESTINATIONS(action.customerId); return this.serviceData .fetch(url, '', {'req': 'get'}).pipe( map((response: PETADestinationsInterface) => { if (!response.destinations) { this.petaStore.dispatch(new LoadPETALoading(false)); return new petaDestinationsActions.PETADestinationsSetToDefaultAction(); } else { return new petaDestinationsActions.LoadPETADestinationsSuccessAction(response); } }), catchError(err => { this.petaStore.dispatch(new LoadPETALoading(false)); this.petaStore.dispatch(new LoadPETAError(true)); return of(new errorActions.ToggleApiError(err, errorUrl, (url))); }) ); })); constructor( private actions$: Actions, private serviceData: DataFetcher, private petaStore: Store ) {} }