(Solved) Bad getting data from local storage

Hi there!

I’m getting data from storage in this way:

       let token;
       this.storage.get('token').then((val) => {
         token =  'Bearer '+val;
         console.log(token);
       });

The data has gotten correctly, i guess . . . Because i print the token variable with console.log and the result in the console is the expected.

imagen

However, when i put the token in the header and make the http request something is wrong.

      let headers = new HttpHeaders({
        'Authorization': token
      });

      this.http.get(API_URL+'mesas_active', { headers })
      .subscribe(data => {
        resolve(data);
      }, err => {
        resolve(err);
      });

When i print the data obtained shows me the next error:

imagen

Then i tried set the token variable putting the token directly in the code, like a string. In this way:

token = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImFiOGJmNjkzMTg5YTM0ODA2ZTRhZmI1YTg5Y2JhYTVhODdkNjBiNzM0MmEyNjRiMjJkNTA5MDNmMzJmMDAzOWZlNTZmYjA1ZDkxNDVhY2RhIn0.eyJhdWQiOiIxIiwianRpIjoiYWI4YmY2OTMxODlhMzQ4MDZlNGFmYjVhODljYmFhNWE4N2Q2MGI3MzQyYTI2NGIyMmQ1MDkwM2YzMmYwMDM5ZmU1NmZiMDVkOTE0NWFjZGEiLCJpYXQiOjE1NDQxODQwOTksIm5iZiI6MTU0NDE4NDA5OSwiZXhwIjoxNTc1NzIwMDk5LCJzdWIiOiIyIiwic2NvcGVzIjpbXX0.aQfoYw3J-VKgoy6GlsZ9dC1Bf1KR84tkQg_AHqer46vMhS_msgidX3Lm-9cA9ZOiSR1BFz69jZtjaw1mW9WQsa83VZ9XqqgbT_gb1Jc794IcbUhSv9cHaGoqB5JwrFhub8UAHpo1sAJleibYcABQk9Kaz_wZgBHDnjo8QrrQYgrbw-HNo1cCCGqNm0v84fGzu5FxsKZp_2hCEwVpr53RJ9J8bnFVTCfojbZP3d9upaCnLGFuJek-mp68GVK9di7p-SAdXlbtsFVJ8TNTO_4WIT5XlH8OqEajzQQjwBe8h2KlqGXvof7HOvnvWgBXB0S5tv7qLJ8bY9XOpQQQDWUZiP8Dckc_4FseME0DRjzFfIDn1IxvpRk7hiHeq-5Ce8B9k-UjCEgUxnrIfaID7Fws4KNjnXdJVs-wqwxEkbuKHiRrWIIM0O4IZvfpP9wN54GIgLwavNausAcAeaMN5PPhoCmBEEI_qkjGh79ATozu81j-DwdzXhRo6RS5C2zzqlCIvY062WuUQ_LAdqXD7CTNv2NYP_DsCopbSTWAGFWO5zS7nNAjNCGO0WUwyUSwMKC2hOeJm4fTDo4edz_3bzIn9ePJg78Y3ppWsSzGZBq8c5EVoeStoUs9LyTUVfS2lDyOjkxLjnr8DAxopl6eIaGxauynZ3RfZk-A_RIPCBV-V10';

When i run the project again the data is requested correctly, without errors.

I can not understand, why it works in the second way, if it is the same token.

It occurs to me that maybe the data obtained from Storage brings properties that make the conversion to String not done correctly. In that case, In that case, i tried casting the data obtained with String(data) but i haven’t success:

      this.storage.get('token').then((val) => {
         token =  'Bearer '+String(val);
         console.log(token);
      });

Could someone tell me the reason why it does not work by getting the data directly from the Storage? I’ll thank you with my soul, I’ve been trying to solve this for a long time.

Thank you in advance.

Because of timing.

Retrieving from storage is an asynchronous operation. I assume you are surrounding the snippet from your http request with new Promise. Don’t do that.

This snippet:

 let token;
 this.storage.get('token').then((val) => {
   token =  'Bearer '+val;
   console.log(token);
 });

…is totally broken. You have no idea when token has what value. Read this post and rewrite this section to be a type 3 function, returning the Promise you get from storage. The code that actually does anything with token must live in a then block when it resolves.

Thank you very much! Your answer really helped me. I found 2 ways to solve the issue, based on your answer.

Method 1:

Following exactly your instructions. I make a function that returns a Promise with the stored data.

  getToken(){
    return new Promise(resolve => {
      this.storage.get('token').then((val) => {
        resolve(val);
      });
    });
  }

And getting the data in the other function:

        this.getToken().then((val) => {
          let token = 'Bearer '+val;

          let headers = new HttpHeaders({
            'Authorization': token
          });

          this.http.get(constantes.API_URL+'mesas_active', { headers })
          .subscribe(data => {
            resolve(data);
          }, err => {
            resolve(err);
          });
        });

It works!! :muscle:

Method 2:

Placing the http request and the header assignment of the request, inside the “.then” section of the storage getter.

      this.storage.get('token').then((val) => {
        let token = 'Bearer '+val;

        let headers = new HttpHeaders({
          'Authorization': token
        });

        this.http.get(constantes.API_URL+'mesas_active', { headers })
        .subscribe(data => {
          resolve(data);
        }, err => {
          resolve(err);
        });
      });

It works too!! :ok_hand:

I’ll stay with option two. Again, thank you very much for your quick response. Sorry to answer you late.

The first part of option 1 is overly complicated, and can just be:

getToken(): Promise<string> {
  return this.storage.get('token');
}