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

前端 未结 2 773

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

        
相关标签:
2条回答
  • 2020-12-15 06:03

    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 }));
    
    0 讨论(0)
  • 2020-12-15 06:16

    Effects don't have to be class properties; they can be methods, too. Which means you can access a store that's injected into the constructor.

    At the time of writing this answer, the semantics of property declarations and public/private constructor parameters were not clear to me. If properties are declared after the constructor, they can access the public/private members declared via constructor parameters - so you don't have to declare your effects as functions.

    With the injected store, you should be able to use an operator like mergeMap to get the state and combine it with the update you received:

    @Effect()
    bar$(): Observable<Action> {
    
      return this.actions$
        .ofType(ActionTypes.FOO)
        .mergeMap((update) => this.store.first().map((state) => ({ state, update })))
        .map((both) => {
          // Do whatever it is you need to do with both.update and both.state.
          return both.update;
        })
        .distinctUntilChanged()
        .filter(x => x)
        .map(() => ({ type: ActionTypes.BAR }));
      }
    }
    

    Whether or not doing this is good practice is a matter of opinion, I guess. Reading the state - ideally by composing an ngrx-style selector - sounds reasonable, but it would be cleaner if all of the information you needed for a particular effect was included in the action to which it was listening.

    0 讨论(0)
提交回复
热议问题