/
regions.effects.ts
30 lines (26 loc) · 1.17 KB
/
regions.effects.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { Store, select } from '@ngrx/store';
import { filter, map, mergeMap, withLatestFrom } from 'rxjs/operators';
import { CountryService } from 'ish-core/services/country/country.service';
import { mapErrorToAction, mapToPayloadProperty } from 'ish-core/utils/operators';
import { loadRegions, loadRegionsFail, loadRegionsSuccess } from './regions.actions';
import { getAllRegions } from './regions.selectors';
@Injectable()
export class RegionsEffects {
constructor(private actions$: Actions, private store: Store, private countryService: CountryService) {}
loadRegions$ = createEffect(() =>
this.actions$.pipe(
ofType(loadRegions),
mapToPayloadProperty('countryCode'),
withLatestFrom(this.store.pipe(select(getAllRegions))),
filter(([countryCode, allRegions]) => !allRegions.some(r => r.countryCode === countryCode)),
mergeMap(([countryCode]) =>
this.countryService.getRegionsByCountry(countryCode).pipe(
map(regions => loadRegionsSuccess({ regions })),
mapErrorToAction(loadRegionsFail)
)
)
)
);
}