import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { Effect, Actions, ofType } from '@ngrx/effects'; import { of, Observable } from 'rxjs'; import { catchError, exhaustMap, map, tap, withLatestFrom } from 'rxjs/operators'; import { MetaCrawler } from '@overflow/commons-typescript/model/meta'; import { MetaCrawlerService } from '../../../service/meta-crawler.service'; import { ReadAll, ReadAllSuccess, ReadAllFailure, ActionType, } from './meta-crawler.action'; import { MetaCrawlerEntitySelector, } from '../../'; @Injectable() export class Effects { constructor( private actions$: Actions, private store$: Store, private metaCrawlerService: MetaCrawlerService, ) { } @Effect() readAll$ = this.actions$.pipe( ofType(ActionType.ReadAll), withLatestFrom(this.store$.select(MetaCrawlerEntitySelector.selectAll)), exhaustMap(([action, results]) => { if (0 < results.length) { return of(new ReadAllSuccess(results)); } return this.metaCrawlerService .readAll() .pipe( map((result: MetaCrawler[]) => { return new ReadAllSuccess(result); }), catchError(error => of(new ReadAllFailure(error))) ); } ) ); }