SHARE
TWEET

Untitled

a guest Jun 20th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Injectable } from '@angular/core';
  2.  
  3. @Injectable()
  4. export class SharedService {
  5.  
  6.     constructor(){}
  7.     //
  8.     set(identifier:string, value:any){
  9.         storage[identifier] = value;
  10.         return storage[identifier];
  11.     }
  12.  
  13.     get(identifier:string){
  14.         if(typeof storage[identifier] === 'undefined'){
  15.             return null;
  16.         }
  17.         return storage[identifier];
  18.     }
  19.  
  20.     remove(identifier:string){
  21.         delete storage[identifier];
  22.     }
  23.  
  24. }
  25.  
  26. export function Shared(identifier:string){
  27.     return function (target: any, key: string){
  28.  
  29.         // property getter
  30.         var getter = function(){
  31.             if(typeof storage[identifier] === 'undefined'){
  32.                 return null;
  33.             }
  34.             return storage[identifier];
  35.         };
  36.    
  37.         // property setter
  38.         var setter = function(newVal){
  39.             let guardName:string = '__-' + key + '-_can_be_overriden';
  40.             if(typeof storage[identifier] === 'undefined'){
  41.                 storage[identifier] = newVal;
  42.             } else if ( this[guardName]){
  43.                 storage[identifier] = newVal;
  44.             }
  45.  
  46.             this[guardName] = true;
  47.         };
  48.    
  49.         // Delete property.
  50.         if (delete target[key]){
  51.  
  52.             // Create new property with getter and setter
  53.             Object.defineProperty(target, key, {
  54.                 get: getter,
  55.                 set: setter,
  56.                 enumerable: true,
  57.                 configurable: true
  58.             });
  59.         }
  60.     }
  61. }
  62.  
  63. let storage:{[key:string]:any} = {};
  64.  
  65.  
  66. /*Usage Example:
  67. @Component({...}) class className implements ngOnInit{
  68.     ...
  69.     @Shared('identifier') variable:string = 'default value.';
  70.     constructor(){...}
  71.     ngOnInit(){
  72.       //change value in storage
  73.       this.variable = 'some other value';
  74.     }
  75.     ...
  76. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top