Source Code
https://github.com/JimTheMan/Jims-Ngrx-Example
Why @Effects?
A Separate Service For Async
Installing Ngrx/Effects
npm install @ngrx/effects --save
Add RunEffects To Your NgModule
import { StoreModule } from '@ngrx/store'; import { MainStoreReducer } from './state-management/reducers/main-store-reducer'; import { EffectsModule } from '@ngrx/effects'; import { MainEffects } from "./state-management/effects/main-store-effects"; @NgModule({ imports: [ StoreModule.provideStore({mainStoreReducer}), EffectsModule.run(MainEffects), ] ] }) export class AppModule { }
Create An Effects Class
import {Effect, Actions, toPayload} from "@ngrx/effects"; import {Injectable} from "@angular/core"; import {Observable} from "rxjs"; @Injectable() export class MainEffects { constructor(private action$: Actions) { } }
Hello World @Effect
@Effect() update$ = this.action$ .ofType('SUPER_SIMPLE_EFFECT') .switchMap( () => Observable.of({type: "SUPER_SIMPLE_EFFECT_HAS_FINISHED"}) );
Payload Example
@Effect() effectWithPayloadExample$ = this.action$ .ofType('SEND_PAYLOAD_TO_EFFECT') .map(toPayload) .switchMap(payload => { console.log('the payload was: ' + payload.message); return Observable.of({type: "PAYLOAD_EFFECT_RESPONDS", payload: {message: "The effect says hi!"}}) });
Async Effect With A Timer
@Effect() timeEffect = this.action$ .ofType('SET_TIMER') .map(toPayload) .switchMap(payload => Observable.timer(payload.seconds * 1000) .switchMap(() => Observable.of({type: "TIMER_FINISHED"}) ) )
Pulling Data From Firebase With AngularFire2
npm i angularfire2 --save
Async Effect Pull Array From Firebase
@Effect() pullArrayFromFirebase$ = this.action$ .ofType('PULL_ARRAY_FROM_FIREBASE') .switchMap( () => this.af.database.list('/cypherapp/rooms/') .switchMap(result => Observable.of({type: "GOT_FIREBASE_ARRAY", payload: {pulledArray: result}}) ) )
Async Effect Pull Object From Firebase
@Effect() pullObjectFromFirebase$ = this.action$ .ofType('PULL_OBJECT_FROM_FIREBASE') .switchMap( () => this.af.database.object('/cypherapp/rooms/') .switchMap(result => Observable.of({type: "GOT_FIREBASE_OBJECT", payload: {pulledObject: result}}) ) )
SwitchMap Just Takes A Function
@Effect() pullObjectFromFirebase$ = this.action$ .ofType('PULL_OBJECT_FROM_FIREBASE') .switchMap(() => { console.log('in the first switchMap!'); return this.af.database.object('/cypherapp/rooms/') .switchMap(result => { console.log('oh yeah, we got the result!'); return Observable.of({type: "GOT_FIREBASE_OBJECT", payload: {pulledObject: result}}) }) });