Search code examples
angularangular5angular-directiveangular-componentsweb-storage

How to store a value locally to a variable even after the page reloads in angular 5


I have used WebStorageServie in my angular 5 application to store a value that is selected once and is accessible to the whole application. It works all fine but when the page is reloaded the data stored in the variable gets refreshed too. The following code shows how i have implemented `WebStorageService' :

constructor(
    private _http: HttpClient,
    @Inject(LOCAL_STORAGE) private storage: WebStorageService
  ) {
    this.setHeaders();
  }

  setHeaders() {
    this.headers =  new HttpHeaders().set('Content-Type', 'application/json');
  }
  /*JIF*/

  setJIF(key1, jifId, key2,  PoID) { // Setting Global Var
            this.storage.set(key1, jifId);
      this.jifId = this.storage.get(key1);
      this.setPO(key2 , PoID);

  }

  setPO(key2, PoID) {
    this.storage.set(key2, PoID);
    this.poId = this.storage.get(key2);
     console.log('POID', this.poId); // Gives Desired Output
    console.log('JIFID', this.jifId);//Gives Desired Output
  }
}

I want the this.jifId and this.poId to retain its value till the user decides otherwise. And the way i am doing it now it gets emptied when the page reloads.


Solution

  • Use Local Storage

    First Set Item Stuff(Like if you want to set loggedInfo)

    let loggedInfo = {'poId':3,'poId':11}
    localStorage.setItem('loggedInfo',JSON.stringify(loggedInfo));
    //Convert Object to String
    

    Now get your Object via getItem

    let loggedData = JSON.parse(localStorage.getItem('loggedInfo'));
    //Convert String to Object and Local Storage data
    

    Now Use you Local Storage data for Further use…:)