]>
Commit | Line | Data |
---|---|---|
ab32b0fc C |
1 | |
2 | import { Injectable } from '@angular/core'; | |
3 | ||
4 | @Injectable() | |
5 | export class AppState { | |
6 | _state = { }; | |
7 | ||
8 | constructor() { ; } | |
9 | ||
10 | // already return a clone of the current state | |
11 | get state() { | |
12 | return this._state = this._clone(this._state); | |
13 | } | |
14 | // never allow mutation | |
15 | set state(value) { | |
16 | throw new Error('do not mutate the `.state` directly'); | |
17 | } | |
18 | ||
19 | ||
20 | get(prop?: any) { | |
21 | // use our state getter for the clone | |
22 | const state = this.state; | |
23 | return state.hasOwnProperty(prop) ? state[prop] : state; | |
24 | } | |
25 | ||
26 | set(prop: string, value: any) { | |
27 | // internally mutate our state | |
28 | return this._state[prop] = value; | |
29 | } | |
30 | ||
31 | ||
32 | _clone(object) { | |
33 | // simple object clone | |
34 | return JSON.parse(JSON.stringify( object )); | |
35 | } | |
36 | } |