How to add dynamic key value in localStorage in angular using a service

Viewed 36
import { Injectable, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { share } from 'rxjs/operators';

@Injectable()
  export class StorageService implements OnDestroy {
    private onSubject = new Subject<{ key: string, value: any }>();
    public changes = this.onSubject.asObservable().pipe(share());

  constructor() {
   this.start();
 }

  ngOnDestroy() {
   this.stop();
}

     public store(key: string, data: any): void {
       localStorage.setItem(key, JSON.stringify(data));
       this.onSubject.next({ key: key, value: data})
}

I am using storageService to store localStorage like -

 if(this.jsp_url){
    this.storageService.store('jsp_isTagEnabled', true);
    this.storageService.store('jsp_dmReload', true);
    
}else{
    this.storageService.store('isTagEnabled', true);
    this.storageService.store('dmReload', true);
  }

i am adding jsp_ statically based on condition, for now, how can i add it dynamically.

1 Answers

I don't quite understand your question. What do you mean by dynamic? Angular has a virtual DOM, you should pass the class to a constructor (dependency inversion principle). You can then use this passed class in your father class.

 import { Injectable } from '@angular/core';
        
        

@Injectable({
      providedIn: 'root'
    })
    export class LocalService {
    
      constructor() { }
    
      public saveData(key: string, value: string) {
        localStorage.setItem(key, value);
      }
    
      public getData(key: string) {
        return localStorage.getItem(key)
      }
      public removeData(key: string) {
        localStorage.removeItem(key);
      }
    
      public clearData() {
        localStorage.clear();
      }
    }

You can then simply import them and include them in the Constructor.

import { LocalService } from './local.service';
export class AppComponent {

  constructor(private localStore: LocalService) {

  }
Related