Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get access of the state tree in effects? (@ngrx/effects 2.x)

Tags:

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 })); 
like image 850
Hongbo Miao Avatar asked Sep 19 '16 05:09

Hongbo Miao


People also ask

How do I get my state from NGRX?

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.

How do you call an effect in NGRX?

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.

How does NGRX effect work?

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.

What are side effects in NGRX?

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.


1 Answers

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 })); 
like image 126
Hongbo Miao Avatar answered Sep 22 '22 21:09

Hongbo Miao