all files / app/ app.service.ts

95% Statements 19/20
50% Branches 1/2
85.71% Functions 6/7
94.44% Lines 17/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54            1× 1×               1× 12×     12×     12×       1× 18×               1×   18× 18×     1×   8× 8×       1×   18×   1×  
/* Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 */
 
import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
 
export type InternalStateType = {
  [key: string]: any
};
 
@Injectable()
export class AppState {
  _state: InternalStateType = { };
 
  public onChange: Observable<any>;
  private changeEvent = new Subject<any>();
 
  constructor() {
        this.onChange = this.changeEvent.asObservable();
  }
 
  // already return a clone of the current state
  get state() {
    return this._state = this._clone(this._state);
  }
  // never allow mutation
  set state(value) {
    throw new Error('do not mutate the `.state` directly');
  }
 
 
  get(prop?: any) {
    // use our state getter for the clone
    const state = this.state;
    return state.hasOwnProperty(prop) ? state[prop] : state;
  }
 
  set(prop: string, value: any) {
    // internally mutate our state
    this._state[prop] = value;
    this.changeEvent.next();
  }
 
 
  private _clone(object: InternalStateType) {
    // simple object clone
    return JSON.parse(JSON.stringify( object ));
  }
}