2

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.

Atul Stha
  • 1,404
  • 8
  • 23
  • 46
  • Any reason why you dont use cookies or localStorage? – Shift 'n Tab May 14 '18 at 05:04
  • no reason i am somewhat new to angular so i might just not have known the way. The process should not be done using cookies but i dont know how to use localStorage – Atul Stha May 14 '18 at 06:13
  • @AtulStha, I may be mistaken, but I can't tell what you're trying to do from your code snippet. I can't tell when setJif is called. However, it seems like you are not 'get'ting the values when the application reloads, so you won't have access to the values. Try doing a getitem() in the constructor – Beartums May 14 '18 at 06:27

1 Answers1

2

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…:)

Aneri Vala
  • 528
  • 3
  • 11