Guest User

Untitled

a guest
Mar 23rd, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. // actions.ts
  2. const STORAGE = '@ngrx/store/storage';
  3.  
  4. export class Storage implements Action {
  5. readonly type = STORAGE;
  6. constructor(readonly payload: string) {}
  7. }
  8.  
  9. // reducers.ts
  10. import { localStorageSync, rehydrateApplicationState } from 'ngrx-store-localstorage';
  11.  
  12. export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  13. return (state: State, action: All) => {
  14. const keys = ['key1', 'key2'];
  15.  
  16. if (action.type === STORAGE && keys.includes(action.payload)) {
  17. const rehydratedState = rehydrateApplicationState([action.payload], localStorage, k => k);
  18. return { ...state, ...rehydratedState };
  19. }
  20.  
  21. return localStorageSync({
  22. keys,
  23. rehydrate: true,
  24. })(reducer)(state, action);
  25. }
  26. }
  27.  
  28. // app.component.ts
  29. export class AppComponent implements OnInit {
  30. constructor(
  31. private readonly renderer: Renderer2,
  32. private readonly store: Store<State>,
  33. ) {}
  34.  
  35. ngOnInit() {
  36. this.renderer.listen('window', 'storage', event => {
  37. this.store.dispatch(new Storage(event.key));
  38. });
  39. }
  40. }
Add Comment
Please, Sign In to add comment