Skip to content

Instantly share code, notes, and snippets.

@webmasterdevlin
Last active March 15, 2019 01:16
Show Gist options
  • Save webmasterdevlin/58f896b9f7f0b4d30dc15307d3269a30 to your computer and use it in GitHub Desktop.
Save webmasterdevlin/58f896b9f7f0b4d30dc15307d3269a30 to your computer and use it in GitHub Desktop.
NgRx Effects : src/app/effects/hero.effects.ts
import { Injectable } from "@angular/core";
import { Actions, Effect, ofType } from "@ngrx/effects";
import { HeroService } from "../heroes/hero.service";
import { Observable, of } from "rxjs";
import { Action } from "@ngrx/store";
import * as heroActions from "../actions/hero.actions";
import {
catchError,
exhaustMap,
map,
mapTo,
mergeMap,
tap
} from "rxjs/operators";
import { Hero } from "../models/hero.model";
@Injectable()
export class HeroEffects {
constructor(private actions$: Actions, private heroService: HeroService) {}
@Effect() // Effect from @ngrx/effects
loadHeroes$: Observable<Action> = this.actions$.pipe(
ofType(heroActions.HeroActionTypes.LoadHeroes), // sends LoadHeroes action
tap(val => console.log("BEFORE MAP:", val)),
mergeMap(() =>
this.heroService.getHeroes().pipe(
map(heroes => new heroActions.LoadHeroesSuccess(heroes)), // if successful, activates LoadHeroesSuccess action with response payload
catchError(err => of(new heroActions.LoadHeroesFail(err))) // if not successful, activates LoadHeroesFail action with error payload
)
),
tap(val => console.log("AFTER MAP:", val))
);
@Effect()
createHero$: Observable<Action> = this.actions$.pipe(
ofType(heroActions.HeroActionTypes.CreateHero),
map((action: heroActions.CreateHero) => action.payload), // sends CreateHero action
mergeMap((hero: Hero) =>
this.heroService.addHero(hero).pipe(
map(newHero => new heroActions.CreateHeroSuccess(newHero)), // if successful, activates CreateHeroSuccess with response payload
catchError(err => of(new heroActions.CreateHeroFail(err))) // if not successful, activates CreateHeroFail action with error payload
)
)
);
@Effect()
updateHero$: Observable<Action> = this.actions$.pipe(
ofType(heroActions.HeroActionTypes.UpdateHero),
map((action: heroActions.UpdateHero) => action.payload),
mergeMap((hero: Hero) =>
this.heroService.updateHero(hero).pipe(
map(updatedHero => new heroActions.UpdateHeroSuccess(updatedHero)),
catchError(err => of(new heroActions.UpdateHeroFail(err)))
)
)
);
@Effect()
deleteHero$: Observable<Action> = this.actions$.pipe(
ofType(heroActions.HeroActionTypes.DeleteHero),
map((action: heroActions.DeleteHero) => action.payload),
mergeMap((hero: Hero) =>
this.heroService.removeHero(hero.id).pipe(
map(() => new heroActions.DeleteHeroSuccess(hero.id)),
catchError(err => of(new heroActions.DeleteHeroFail(err)))
)
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment