File

projects/web-mev/src/app/core/local-storage/storage.service.ts

Index

Properties
Methods

Constructor

constructor(storage: Storage)

Constructor with service injection

Parameters :
Name Type Optional
storage Storage No

Methods

clear
clear()

clear all available keys

Returns : void
get
get(key: string)

get data of given key

Parameters :
Name Type Optional
key string No
Returns : any
remove
remove(key: string)

remove given key

Parameters :
Name Type Optional
key string No
Returns : void
set
set(key: string, value: any)

set value on given key

Parameters :
Name Type Optional
key string No
value any No
Returns : void
watch
watch(key: string)

watch data of given key

Parameters :
Name Type Optional
key string No
Returns : Observable<any>

Properties

Private storage
Type : Storage
Private subjects
Type : Map<string | BehaviorSubject<any>>
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class StorageService {
  private storage: Storage;
  private subjects: Map<string, BehaviorSubject<any>>;

  /**
   * Constructor with service injection
   * @param storage
   */
  constructor(storage: Storage) {
    this.storage = storage;
    this.subjects = new Map<string, BehaviorSubject<any>>();
  }

  /**
   * watch data of given key
   * @param key
   * @param defaultValue
   */
  watch(key: string): Observable<any> {
    if (!this.subjects.has(key)) {
      this.subjects.set(key, new BehaviorSubject<any>(null));
    }
    let item = this.storage.getItem(key);
    if (item === 'undefined') {
      item = undefined;
    } else {
      item = JSON.parse(item);
    }
    this.subjects.get(key).next(item);
    return this.subjects.get(key).asObservable();
  }

  /**
   * get data of given key
   * @param key
   */
  get(key: string): any {
    let item = this.storage.getItem(key);
    if (item === 'undefined') {
      item = undefined;
    } else {
      item = JSON.parse(item);
    }
    return item;
  }

  /**
   * set value on given key
   * @param key
   * @param value
   */
  set(key: string, value: any) {
    this.storage.setItem(key, JSON.stringify(value));
    if (!this.subjects.has(key)) {
      this.subjects.set(key, new BehaviorSubject<any>(value));
    } else {
      this.subjects.get(key).next(value);
    }
  }

  /**
   * remove given key
   * @param key
   */
  remove(key: string) {
    if (this.subjects.has(key)) {
      this.subjects.get(key).complete();
      this.subjects.delete(key);
    }
    this.storage.removeItem(key);
  }

  /**
   * clear all available keys
   */
  clear() {
    this.subjects.clear();
    this.storage.clear();
  }
}

result-matching ""

    No results matching ""