UPDATE: After thoroughful considerations, I think your requirement is problematic: if you store the backedUp
flag in your state, then once the flag is updated (to false
), it will trigger the store to be backed up. Then after the store has been backed up, the flag should be updated to true
, this will trigger the store to be backed up again. This will happens on and on forever.
This's what I have in mind at the moment:
- Create the
backUp
store feature:
You can put the backedUp
flag in there, your store might look like:
{
...
backUp: {
backedUp: boolean;
backingUp: boolean; // optional
lastVersion: string; // optional
...
}
}
- Create
BACK_UP_STORE_ACTION
and STORE_BACKED_UP_ACTION
.
- Create two effects to watch and back up the store:
You may want to write it like this:
constructor(private actions$: Actions,
private store: Store<fromRoot.State>,
private backUpStoreService: BackUpStoreService) {
}
@Effect()
watchState$ = this.store
.debounceTime(1000) // save store 1 second after the last change, preventing API spamming
.map(state => new storeBackUp.BackUpStoreAction(state));
@Effect()
backUpState$ = this.actions$
.ofType(storeBackUp.BACK_UP_STORE_ACTION)
.concatMap((action: storeBackUp.BackUpStoreAction) => this.backUpStoreService.backUp(action.payload))
.map(response => new storeBackUp.StoreBackedUpAction(response));
- Create a meta reducer to update the
backedUp
flag.
Here is the sudo code for the meta reducer, this meta-reducer check on every action, if the action is BACK_UP_STORE_ACTION
, it will set the backedUp
flag to false; if the action is STORE_BACKED_UP_ACTION
, it will set the backedUp
flag to true.
export function storeBackUpMetaReducer(reducer: ActionReducer<State>): ActionReducer<State> {
return function (state: State, action: any): State {
if (action.type === storeBackUp.STORE_BACKED_UP_ACTION) {
state.backUp.backedUp = true;
} else if (action.type === storeBackUp.BACK_UP_STORE_ACTION) {
state.backUp.backedUp = false;
}
return reducer(state, action);
};
}
- Now you can watch on the
backedUp
flag to prompt the use when they want to exit before the store has been saved.