[UPDATE 2022]
This blog post works like a charm for Angular 14 and very easy to implement. You can use any action to reset store. https://www.purcellyoon.com/insights/articles/angular-ngrx-8-reset-state-using-meta-reducer
Define logout action in actions.ts
import { createAction, props } from '@ngrx/store';
export const logoutSuccess = createAction('[Authentication] Logout Success');
Define your MetaReducer in reducers.ts
import { ActionReducer, ActionReducerMap, INIT, MetaReducer } from '@ngrx/store';
import * as AuthActions from './actions';
export const reducers: ActionReducerMap<State> = {
[featureKey1]: reducer1,
[featureKey2]: reducer2,
//...
}
export const logout = (reducer: ActionReducer<any>): ActionReducer<any> => {
return (state, action) => {
if (action !== null && action.type === AuthActions.logoutSuccess.type) {
return reducer(undefined, { type: INIT });
}
return reducer(state, action);
};
};
export const metaReducers: MetaReducer[] = [logout];
app.store.module.ts
import { metaReducers, reducers } from '../store/reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, {
metaReducers,
runtimeChecks: {
strictStateImmutability: true,
strictActionImmutability: true
}
}),
Now dispatch your action in the component
this.store.dispatch(logout());
In effects, dispatch logout success action so that the user logs out and the store is reset.
logout$ = createEffect(() => this.actions$.pipe(
ofType(Actions.logout),
mergeMap((action) =>
this.apiService.logout().pipe(
map((user: User) => Actions.logoutSuccess()),
catchError((error) => of(Actions.logoutFailure({ error })))
)
)
));