Marwa
Marwa

Reputation: 321

Error: Property 'token' does not exist on type 'Storage'

In my authentication service file in the ionic front-end, I am trying to get the token from the local storage through the following lines of code inside the constructor's body:

` constructor(private http: Http) {
    this.token = window.localStorage.token;
    if (this.token) {
      this.authorized = true;
    } else {
      this.authorized = false;
    }
  }`

I am also trying to set the token inside a method called setToken:

 setToken(token: string) {
    this.token = token;
    window.localStorage.token = this.token;
    this.authorized = true;
  }

However, VS code is displaying an error message in both cases when I hover over the word token on the RHS. Property 'token' does not exist on type 'Storage' What is there that I am doing wrong?

Upvotes: 1

Views: 359

Answers (1)

Marco Chavez
Marco Chavez

Reputation: 365

you don't use correctly the local Storage, in short:

To save data, use the code:

localStorage.setItem("UNIQUE_NAME_ITEM", variable);

To retrieve some Item, use the code:

localStorage.getItem("UNIQUE_NAME_ITEM")

Also, be carefully when try to retrieve an Item that is not save yet, it will return a null or undefined.

I hope I've helped :)

Upvotes: 2

Related Questions