How to reset all states of ngrx/store?

后端 未结 4 735
执笔经年
执笔经年 2020-12-15 17:11

I am using Angular 2 with ngrx/store. I want to reset the whole store states when user dispatch USER_LOGOUT.

I read the Dan Abramov\'s answer of How to

4条回答
  •  -上瘾入骨i
    2020-12-15 17:47

    This answer is specific to ngrx version 2. The question has another, more recent answer that explains how the same can be done with ngrx version 4.


    compose builds the ngrx root reducer.

    The arguments passed to compose are functions that return a reducer - composed from the reducer they themselves are passed as an argument. You can compose the resetting of your store like this:

    import { compose } from "@ngrx/core/compose";
    
    ...
    
    bootstrap(App, [
      provideStore(
        compose(
          storeFreeze,
          storeLogger(),
          (reducer: Function) => {
            return function(state, action) {
              if (action.type === 'USER_LOGOUT') {
                state = undefined;
              }
              return reducer(state, action);
            };
          },
          combineReducers
        )({
          router: routerReducer,
          foo: fooReducer,
          bar: barReducer
        })
      )
    ]);
    

    Note that this will reset all of the store's state - including the router. If that's not what you want, you could tweak the example.

    With introduction of NgModule the bootstrapping has changed, but you still pass the composed reducer to provideStore:

    import { compose } from "@ngrx/core/compose";
    import { StoreModule } from "@ngrx/store";
    
    @NgModule({
        ...
        imports: [
            ...
            StoreModule.provideStore(compose(...))
        ],
        ...
    

提交回复
热议问题