I am building an mobile app using Ngrx and Angular2. I would like to clear the Store when user logout from my application? Can anyone know how to do this?
3 Answers
You should have an clear action in each of your reducer, which will clean respective properties in the store. Dispatch clear actions in each of the reducer manually when you call logout
. I am not sure right now if its there an option to clean the entire store in one go.
Alternative:
A more cleaner and faster approach would be. Whenever you call an action via store.dispatch
it calls all your reducers with that action.type
. Say your action type name is CLEAR
, put this action in each of your reducer to clear the respective property of the store. And call store.dispatch
with action.type = 'CLEAR'
ONCE, it will clear all the properties of the store.
If it confuses let me know, I will try to explain with code.

- 1,974
- 1
- 24
- 44
-
Isn't the old state still preserved (the ability that allows state to time travel)? Wouldn't "cleared" objects still be preserved in the memory? – Alex Lomia Oct 27 '17 at 07:10
The solution is to write the root reducer.
It's similar to this:
export function reducer(state: any, action: any): ActionReducer<any> {
if (action.type === 'CLEAR STATE') {
state = undefined;
}
return appReducer(state, action);
}
Check this: How to reset the state of a Redux store?
My guess as to a way to do this would be to have a component that has the store registered on it. Put it in a router-outlet or a structural directive that could force a destroy and init on the component when the value changes.
Since the store is registered as a provider for the component (unless I'm mistaken) and should be tied to it, it should be destroyed when the component is destroyed and a new one created with a new component. Just a thought. I haven't had time to test it.
Don't register the provider in a parent component though. I believe the injectables work through a hierarchy.

- 545
- 4
- 13
-
2I don't understand the down vote. This is a legitimate potential answer. If it didn't work then add it in the comments. If it wasn't the type of answer you wanted then you need to be more specific in your question. – wiredprogrammer Aug 07 '16 at 13:25