@ozexpert wrote:
Having a hard time learning Ngrx effects. I’m using ngrx/store to manage my state. However, I’d like to have Ngrx effects to handle saving to Ionic Storage when state is changed. However, I’m not sure how I can do that.
I have the following code, but dispatching with type UPDATE_SETTINGS won’t get the changed state, so I can’t really change it in the storage. Does anyone have a similar example of using ngrx/effects? anything similar to this would help. Thanks!
import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { Actions, Effect } from "@ngrx/effects"; import { GET_SETTINGS, UPDATE_SETTINGS, UPDATE_SETTINGS_SUCCESS, Action, AppState } from '../_reducers/settings.reducer'; import { StorageProvider } from '../providers/storage/storage'; import { Observable } from "rxjs"; const storageKey = 'settings'; @Injectable() export class SettingsEffects { constructor( private storage: StorageProvider, private actions$: Actions, private store$: Store<AppState> ) {} @Effect() get$ = this.actions$ .ofType(GET_SETTINGS) .mergeMap((action: any) => Observable.fromPromise(this.storage.get(storageKey)) .map(data => ({ type: UPDATE_SETTINGS, payload: data })) .catch(() => Observable.of())) .catch(() => Observable.of()); @Effect() update$ = this.actions$ .ofType(UPDATE_SETTINGS) .switchMap(() => { return Observable.of({ type: "UPDATE_SETTINGS_SUCCESS" }) }); @Effect() updateSuccess$ = this.actions$ .ofType(UPDATE_SETTINGS_SUCCESS) .do(() => { console.log('update settings success called'); }) .withLatestFrom(this.store$) .switchMap(([ payload, store ] : any) => { return Observable.fromPromise(this.storage.set(storageKey, store.settings)) .catch(() => Observable.of()) }) .catch(() => Observable.of()); }
Posts: 1
Participants: 1