-1

I create a simple login form on Angular (v8). On return response, I save it in localStorage like this

this.loginCtrl.login(form.value).subscribe(
     response => {
          console.log(response["token"]); //IS CORRECT
          if (response["token"] != null) {
               localStorage.setItem("token", response["token"]);
           }
       })

Then I want to get the token and send it to other services.

const httpOptions = {
  headers: new HttpHeaders({
    Authorization: "Token " + localStorage.getItem("token")
  })
};

 getGroupsByEntityAndUser(id: string, user: String) {
    return this.http.get(
      "URL" +
        id +
        "/username/" +
        user,
      httpOptions
    );
  }

The problem appears when I load the home page. The console returns that the token is null so the response is null. When I refresh the page with F5 I get the token and getGroupsByEntityAndUser function works properly. It´s a bit strange.

So the question is: Why when I load the first time localStorage is null but when I refresh the page is filled? It is necessary to be filled without refresh.

Keeano
  • 309
  • 8
  • 33
El Hombre Sin Nombre
  • 2,906
  • 18
  • 49
  • 92

2 Answers2

0

The localStorage.getItem-method is asynchronous, please use fat arrow function to catch the result when available, like here:

try {
      this.storage.get('eqs').then( eqlist => {
        let _entries = JSON.parse(eqlist);
        _entries.forEach( el => {
          this.savedEQs.push(el);
        });

      });
    } catch (e) {
      console.log('no entries found!');
    }
  }
Bonzo
  • 427
  • 2
  • 10
  • 28
Micha
  • 906
  • 6
  • 9
0
 this.loginCtrl.login(form.value).subscribe(
    async (response) => {
         await this.handleToken(response);
          // Execute your Next Code
      });
  handleToken(data) {
    if (!localStorage.getItem('token')) {
      localStorage.setItem('token', data.token);
    }
  }
Rushi Patel
  • 561
  • 4
  • 14