I am updating @ngrx/effects from 1.x to 2.x
In 1.x I have access of state tree in effect:
constructor(private updates$: StateUpdates<AppState>) {} @Effect() bar$ = this.updates$ .whenAction(Actions.FOO) .map(obj => obj.state.user.isCool) .distinctUntilChanged() .filter(x => x) .map(() => ({ type: Actions.BAR }));
Now in 2.x, it only gives me action. Is there still a way to get access of the state tree? Or should I avoid using like this because it is not a good practice?
constructor(private actions$: Actions) {} @Effect() bar$ = this.actions$ .ofType(ActionTypes.FOO) .map((obj: any) => { console.log(obj); // here is action only return obj.state.user.isCool // so it is wrong here }) .distinctUntilChanged() .filter(x => x) .map(() => ({ type: ActionTypes.BAR }));
To read your application state in Redux, we need to use the select() method on @ngrx's Store class. This method creates and returns an Observable that is bound to a specific property in your application state.
You need to run this command npm install @ngrx/effects — save to install required dependencies. You have to define the actual services to make the API calls. Finally, you need to register all the effects with the EffectsModules and import this module into your main module or feature module.
Most effects are straightforward: they receive a triggering action, perform a side effect, and return an Observable stream of another action which indicates the result is ready. NgRx effects will then automatically dispatch that action to trigger the reducers and perform a state change.
A side effect refers simply to the modification of some kind of state - for instance: Changing the value of a variable; Writing some data to disk; Enabling or disabling a button in the User Interface.
Another way is using .withLatestFrom(this.store)
. So the complete code is:
constructor( private actions$: Actions, private store: Store<AppState> ) {} @Effect() bar$ = this.actions$ .ofType(ActionTypes.FOO) .withLatestFrom(this.store, (action, state) => state.user.isCool) .distinctUntilChanged() .filter(x => x) .map(() => ({ type: ActionTypes.BAR }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With